// OpenLockFile opens the named file with flags os.O_RDWR|os.O_CREATE and specified perm.
// If successful, function returns LockFile for opened file.
2957
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) {
	var file *os.File
	if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil {
		lock = &LockFile{file}
	}
	return
}
1113217
func (l *httpFileSystem) OpenFile(filePath string) (io.ReadCloser, error) {
	if l.reader == nil {
		return nil, trace.BadParameter("missing reader")
	}

	return l.reader, nil
}
1278045
func OpenFile(path string, perm os.FileMode, size int64) (*LogFile, error) {
	l := LogFile{}
	l.path = path
	l.perm = perm
	l.size = size
	l.rate = DefaultRotationRate

	// Search for the first available path
	err := l.searchFirstAvPath()
	if err != nil {
		return nil, err
	}
	// Open the file descriptor
	f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm)
	if err != nil {
		return nil, err
	}
	l.file = f
	l.writer = gzip.NewWriter(f)
	// We start the rotate routine
	l.rotateRoutine()
	return &l, nil
}
154562
func WriteFile(filename string, node Node, perm os.FileMode, opts ...Option) error {
	file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
	if err != nil {
		return err
	}
	defer file.Close()
	return Write(file, node, opts...)
}
1189027
func writeFile(filePath string, data []byte) error {
	f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return fmt.Errorf("opening %s: %s", filePath, err)
	}
	// NOTE: We don't defer f.Close here, because it may return an error.

	_, writeErr := f.Write(data)
	closeErr := f.Close()
	if writeErr != nil {
		return fmt.Errorf("writing %s: %s", filePath, writeErr)
	} else if closeErr != nil {
		return fmt.Errorf("closing %s: %s", filePath, closeErr)
	}
	return nil
}
451234
func NewFile(filename string, data []byte, perm os.FileMode) File {
	return File{filename, data, perm}
}
1118614
func CreateLockFile(file string) (LockFile, error) {
	fname, err := syscall.UTF16PtrFromString(file)
	if err != nil {
		return nil, err
	}
	f, err := syscall.CreateFile(fname,
		syscall.GENERIC_READ|syscall.GENERIC_WRITE,
		0, // dwShareMode: 0 means "Prevents other processes from opening a file or device if they request delete, read, or write access."
		nil,
		syscall.CREATE_ALWAYS,
		syscall.FILE_ATTRIBUTE_NORMAL,
		0,
	)
	if err != nil {
		// TODO: There HAS to be a better way, but I can't seem to
		// find how to get Windows error codes (also syscall.GetLastError()
		// returns nil here).
		if strings.Contains(err.Error(), "used by another process") {
			err = ErrUnableToLockNow
		}
		syscall.CloseHandle(f)
		return nil, err
	}
	return &lockFile{f: f}, nil
}
779101
func (c *Client) OpenFile(path string, f int) (*File, error) {
	return c.open(path, flags(f))
}
1132815
func (c *Client) LockFile(path string) (Lock, error) {
	lockRes, _, err := c.client.Lock(c.Remote, &lockRequest{
		Path: path,
		Ref:  &lockRef{Name: c.RemoteRef.Refspec()},
	})
	if err != nil {
		return Lock{}, errors.Wrap(err, "api")
	}

	if len(lockRes.Message) > 0 {
		if len(lockRes.RequestID) > 0 {
			tracerx.Printf("Server Request ID: %s", lockRes.RequestID)
		}
		return Lock{}, fmt.Errorf("Server unable to create lock: %s", lockRes.Message)
	}

	lock := *lockRes.Lock
	if err := c.cache.Add(lock); err != nil {
		return Lock{}, errors.Wrap(err, "lock cache")
	}

	abs, err := getAbsolutePath(path)
	if err != nil {
		return Lock{}, errors.Wrap(err, "make lockpath absolute")
	}

	// Ensure writeable on return
	if err := tools.SetFileWriteFlag(abs, true); err != nil {
		return Lock{}, err
	}

	return lock, nil
}
1321944
func (f *LockPIDFile) Lock() (err error) {
	pathp, err := syscall.UTF16PtrFromString(f.name)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE)
	createmode := uint32(syscall.OPEN_ALWAYS)
	sharemode := uint32(syscall.FILE_SHARE_READ) // os.Open always uses FILE_SHARE_READ | FILE_SHARE_WRITE
	var sa *syscall.SecurityAttributes
	r, err := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0)
	if err != nil {
		return PIDFileLockError{f.name}
	}
	// this is what os.openFile does
	f.file = os.NewFile(uintptr(r), f.name)

	pid := os.Getpid()
	fmt.Fprintf(f.file, "%d", pid)
	f.file.Sync()

	f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)

	return nil
}
469837
func (l *lockfile) Unlock() {
	lk := unix.Flock_t{
		Type:   unix.F_UNLCK,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
		Pid:    int32(os.Getpid()),
	}
	l.stateMutex.Lock()
	if l.locked == false {
		// Panic when unlocking an unlocked lock.  That's a violation
		// of the lock semantics and will reveal such.
		panic("calling Unlock on unlocked lock")
	}
	l.counter--
	if l.counter < 0 {
		// Panic when the counter is negative.  There is no way we can
		// recover from a corrupted lock and we need to protect the
		// storage from corruption.
		panic(fmt.Sprintf("lock %q has been unlocked too often", l.file))
	}
	if l.counter == 0 {
		// We should only release the lock when the counter is 0 to
		// avoid releasing read-locks too early; a given process may
		// acquire a read lock multiple times.
		l.locked = false
		for unix.FcntlFlock(l.fd, unix.F_SETLKW, &lk) != nil {
			time.Sleep(10 * time.Millisecond)
		}
		// Close the file descriptor on the last unlock.
		unix.Close(int(l.fd))
	}
	if l.locktype == unix.F_RDLCK {
		l.rwMutex.RUnlock()
	} else {
		l.rwMutex.Unlock()
	}
	l.stateMutex.Unlock()
}
542114
func (fs DummyFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
	return nil, fs.err
}
45011
func newRLockedFile(lkFile *LockedFile) (*RLockedFile, error) {
	if lkFile == nil {
		return nil, os.ErrInvalid
	}

	return &RLockedFile{
		LockedFile: lkFile,
		refs:       1,
	}, nil
}
554352
func RLockedOpenFile(path string) (*RLockedFile, error) {
	lkFile, err := LockedOpenFile(path, os.O_RDONLY, 0666)
	if err != nil {
		return nil, err
	}

	return newRLockedFile(lkFile)

}
884585
func OpenFile(filename string) (apk *Apk, err error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err != nil {
			f.Close()
		}
	}()
	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}
	apk, err = OpenZipReader(f, fi.Size())
	if err != nil {
		return nil, err
	}
	apk.f = f
	return
}
1158445
func OpenFile(path string) (*os.File, error) {
	newPath, err := NormalizePath(path)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	fi, err := os.Stat(newPath)
	if err != nil {
		return nil, trace.ConvertSystemError(err)
	}
	if fi.IsDir() {
		return nil, trace.BadParameter("%v is not a file", path)
	}
	f, err := os.Open(newPath)
	if err != nil {
		return nil, trace.ConvertSystemError(err)
	}
	return f, nil
}
329944
func (f *autoclosedFile) ensureOpen() error {
	if f.fd != nil {
		// File is already open
		return nil
	}

	// We open the file for write only, and create it if it doesn't exist.
	flags := os.O_WRONLY | os.O_CREATE
	if f.opened.IsZero() {
		// This is the first time we are opening the file. We should truncate
		// it to better emulate an os.Create() call.
		flags |= os.O_TRUNC
	} else {
		// The file was already opened once, so we should append to it.
		flags |= os.O_APPEND
	}

	fd, err := os.OpenFile(f.name, flags, 0644)
	if err != nil {
		return err
	}

	f.fd = fd
	f.opened = time.Now()
	return nil
}