// Writes a file with read only permissions
// If the file already exists then it returns the specific error: os.ErrExist
// This is thanks to the flag O_CREATE
974439
func writeFile(filename string, data []byte) error {

	if fileExists(filename) {
		return os.ErrExist
	}

	file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0400)
	if err != nil {
		log.Println(err)
		return err
	}

	_, err = file.Write(data)
	return err

}
460834
func Write(s *File, w io.Writer) error {
	diags := writeStateV4(s, w)
	return diags.Err()
}
286538
func (h *fs) Create(filename string) (io.WriteCloser, error) {
	return os.Create(filename)
}
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
}
569246
func (f DumFile) Write(p []byte) (n int, err error) {
	return 0, f.err
}
461170
func (f *File) Write(filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = file.WriteString(f.String())
	return err
}
1299342
func Write(path string) error {
	pid := os.Getpid()
	return write(path, pid)
}
584987
func (d *Diskv) writeStreamWithLock(pathKey *PathKey, r io.Reader, sync bool) error {
	if err := d.ensurePathWithLock(pathKey); err != nil {
		return fmt.Errorf("ensure path: %s", err)
	}

	f, err := d.createKeyFileWithLock(pathKey)
	if err != nil {
		return fmt.Errorf("create key file: %s", err)
	}

	wc := io.WriteCloser(&nopWriteCloser{f})
	if d.Compression != nil {
		wc, err = d.Compression.Writer(f)
		if err != nil {
			f.Close()           // error deliberately ignored
			os.Remove(f.Name()) // error deliberately ignored
			return fmt.Errorf("compression writer: %s", err)
		}
	}

	if _, err := io.Copy(wc, r); err != nil {
		f.Close()           // error deliberately ignored
		os.Remove(f.Name()) // error deliberately ignored
		return fmt.Errorf("i/o copy: %s", err)
	}

	if err := wc.Close(); err != nil {
		f.Close()           // error deliberately ignored
		os.Remove(f.Name()) // error deliberately ignored
		return fmt.Errorf("compression close: %s", err)
	}

	if sync {
		if err := f.Sync(); err != nil {
			f.Close()           // error deliberately ignored
			os.Remove(f.Name()) // error deliberately ignored
			return fmt.Errorf("file sync: %s", err)
		}
	}

	if err := f.Close(); err != nil {
		return fmt.Errorf("file close: %s", err)
	}

	fullPath := d.completeFilename(pathKey)
	if f.Name() != fullPath {
		if err := os.Rename(f.Name(), fullPath); err != nil {
			os.Remove(f.Name()) // error deliberately ignored
			return fmt.Errorf("rename: %s", err)
		}
	}

	if d.Index != nil {
		d.Index.Insert(pathKey.originalKey)
	}

	d.bustCacheWithLock(pathKey.originalKey) // cache only on read

	return nil
}
222728
func writeFile(fs utilfs.Filesystem, path string, data []byte) (retErr error) {
	// Create a temporary file in the base directory of `path` with a prefix.
	tmpFile, err := fs.TempFile(filepath.Dir(path), tmpPrefix)
	if err != nil {
		return err
	}

	tmpPath := tmpFile.Name()
	shouldClose := true

	defer func() {
		// Close the file.
		if shouldClose {
			if err := tmpFile.Close(); err != nil {
				if retErr == nil {
					retErr = fmt.Errorf("close error: %v", err)
				} else {
					retErr = fmt.Errorf("failed to close temp file after error %v; close error: %v", retErr, err)
				}
			}
		}

		// Clean up the temp file on error.
		if retErr != nil && tmpPath != "" {
			if err := removePath(fs, tmpPath); err != nil {
				retErr = fmt.Errorf("failed to remove the temporary file (%q) after error %v; remove error: %v", tmpPath, retErr, err)
			}
		}
	}()

	// Write data.
	if _, err := tmpFile.Write(data); err != nil {
		return err
	}

	// Sync file.
	if err := tmpFile.Sync(); err != nil {
		return err
	}

	// Closing the file before renaming.
	err = tmpFile.Close()
	shouldClose = false
	if err != nil {
		return err
	}

	return fs.Rename(tmpPath, path)
}
1072361
func (dir *Dir) WriteFile(fileName string, reader io.Reader) (file *File, err error) {
	if err = dir.createIfNoExist(); err == nil {
		relativeDir := strings.TrimPrefix(dir.DirPath, dir.Filebox.BaseDir)
		file = dir.Filebox.AccessFile(filepath.Join(relativeDir, fileName), dir.Roles...)
		err = file.Write(reader)
	}
	return
}
1115758
func writeToFile(path string, r io.Reader) error {
	if exists(path) {
		return fmt.Errorf("%v already exists", path)
	}

	dir := filepath.Dir(path)
	if dir != "" {
		if err := os.MkdirAll(dir, 0777); err != nil {
			return err
		}
	}

	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, r)
	return err
}
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...)
}
757800
func safeWriteToFileOnce(g SafeWriteLogger, t SafeWriter, mode os.FileMode) (err error) {
	fn := t.GetFilename()
	g.Debug("+ SafeWriteToFile(%q)", fn)
	defer func() {
		g.Debug("- SafeWriteToFile(%q) -> %s", fn, ErrToOk(err))
	}()

	tmpfn, tmp, err := OpenTempFile(fn, "", mode)
	if err != nil {
		return err
	}
	g.Debug("| Temporary file generated: %s", tmpfn)
	defer tmp.Close()
	defer ShredFile(tmpfn)

	g.Debug("| WriteTo %s", tmpfn)
	n, err := t.WriteTo(tmp)
	if err != nil {
		g.Errorf("| Error writing temporary file %s: %s", tmpfn, err)
		return err
	}
	if n != 0 {
		// unfortunately, some implementations always return 0 for the number
		// of bytes written, so not much info there, but will log it when
		// it isn't 0.
		g.Debug("| bytes written to temporary file %s: %d", tmpfn, n)
	}

	if err := tmp.Sync(); err != nil {
		g.Errorf("| Error syncing temporary file %s: %s", tmpfn, err)
		return err
	}

	if err := tmp.Close(); err != nil {
		g.Errorf("| Error closing temporary file %s: %s", tmpfn, err)
		return err
	}

	g.Debug("| Renaming temporary file %s -> permanent file %s", tmpfn, fn)
	if err := os.Rename(tmpfn, fn); err != nil {
		g.Errorf("| Error renaming temporary file %s -> permanent file %s: %s", tmpfn, fn, err)
		return err
	}

	if runtime.GOOS == "android" {
		g.Debug("| Android extra checks in safeWriteToFile")
		info, err := os.Stat(fn)
		if err != nil {
			g.Errorf("| Error os.Stat(%s): %s", fn, err)
			return err
		}
		g.Debug("| File info: name = %s", info.Name())
		g.Debug("| File info: size = %d", info.Size())
		g.Debug("| File info: mode = %s", info.Mode())
		g.Debug("| File info: mod time = %s", info.ModTime())

		g.Debug("| Android extra checks done")
	}

	g.Debug("| Done writing to file %s", fn)

	return 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
}
939216
func (f *FileRotator) Write(p []byte) (n int, err error) {
	n = 0
	var forceRotate bool

	for n < len(p) {
		// Check if we still have space in the current file, otherwise close and
		// open the next file
		if forceRotate || f.currentWr >= f.FileSize {
			forceRotate = false
			f.flushBuffer()
			f.currentFile.Close()
			if err := f.nextFile(); err != nil {
				f.logger.Error("error creating next file", "err", err)
				return 0, err
			}
		}
		// Calculate the remaining size on this file and how much we have left
		// to write
		remainingSpace := f.FileSize - f.currentWr
		remainingToWrite := int64(len(p[n:]))

		// Check if we are near the end of the file. If we are we attempt to
		// avoid a log line being split between two files.
		var nw int
		if (remainingSpace - lineScanLimit) < remainingToWrite {
			// Scan for new line and if the data up to new line fits in current
			// file, write to buffer
			idx := bytes.IndexByte(p[n:], newLineDelimiter)
			if idx >= 0 && (remainingSpace-int64(idx)-1) >= 0 {
				// We have space so write it to buffer
				nw, err = f.writeToBuffer(p[n : n+idx+1])
			} else if idx >= 0 {
				// We found a new line but don't have space so just force rotate
				forceRotate = true
			} else if remainingToWrite > f.FileSize || f.FileSize-lineScanLimit < 0 {
				// There is no new line remaining but there is no point in
				// rotating since the remaining data will not even fit in the
				// next file either so just fill this one up.
				li := int64(n) + remainingSpace
				if remainingSpace > remainingToWrite {
					li = int64(n) + remainingToWrite
				}
				nw, err = f.writeToBuffer(p[n:li])
			} else {
				// There is no new line in the data remaining for us to write
				// and it will fit in the next file so rotate.
				forceRotate = true
			}
		} else {
			// Write all the bytes in the current file
			nw, err = f.writeToBuffer(p[n:])
		}

		// Increment the number of bytes written so far in this method
		// invocation
		n += nw

		// Increment the total number of bytes in the file
		f.currentWr += int64(n)
		if err != nil {
			f.logger.Error("error writing to file", "err", err)

			// As bufio writer does not automatically recover in case of any
			// io error, we need to recover from it manually resetting the
			// writter.
			f.createOrResetBuffer()

			return
		}
	}
	return
}
349168
func (f *LockPIDFile) Lock() (err error) {
	// make the parent directory
	_, err = os.Stat(filepath.Dir(f.name))
	if os.IsNotExist(err) {
		err = os.MkdirAll(filepath.Dir(f.name), 0700)
		if err != nil {
			return err
		}
	} else if err != nil {
		return err
	}

	if f.file, err = os.OpenFile(f.name, os.O_CREATE|os.O_RDWR, 0600); err != nil {
		return err
	}

	// LOCK_EX = exclusive
	// LOCK_NB = nonblocking
	if err = syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		f.file.Close()
		f.file = nil
		return err
	}

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

	f.log.Debugf("Locked pidfile %s for pid=%d", f.name, pid)

	return nil
}
568613
func (f *RekeyFile) WriteFile(ctx context.Context, fi *dokan.FileInfo, bs []byte, offset int64) (n int, err error) {
	f.folder.fs.logEnter(ctx, "RekeyFile Write")
	defer func() { f.folder.reportErr(ctx, libkbfs.WriteMode, err) }()
	if len(bs) == 0 {
		return 0, nil
	}
	_, err = libkbfs.RequestRekeyAndWaitForOneFinishEvent(ctx,
		f.folder.fs.config.KBFSOps(), f.folder.getFolderBranch().Tlf)
	if err != nil {
		return 0, err
	}
	f.folder.fs.NotificationGroupWait()
	return len(bs), nil
}