Package os contains useful functions for working with file system.
os - The Go Programming Language
Open()
- opens the named file for reading (O_RDONLY mode).
OpenFile()
- opens file in a specified mode set via flag e.g. O_RDWR or O_WRONLY.
Create()
- creates or truncates the named file
- If the file already exists, it is truncated.
- If the file does not exist, it is created.
- Methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR.
Truncate() function:
- requires file to be opened in mode which allows writing into it.
- if specified size is 0 deletes the content of the file and sets its size to 0.
Writing to files
Go by Example: Writing Files
Without buffering:
f, err := os.Create("/tmp/test.txt")
if err != nil {
panic(err)
}
defer f.Close()
f.WriteString("some text!\n")
WriteString() under the hood calls system function write():
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
write() belongs to the group of Unix unbuffered file I/O functions (together with open, close, read, lseek...).
From FILE I/O:
They are part of the POSIX standard for UNIX programming, not part of ANSI C. Unlike the standard I/O routines provided by ANSI C (such as fscanf and fprintf which store the data they read in buffers) these functions are unbuffered I/O. They invoke a system call in the kernel, and will be called by the standard ANSI C function calls in the UNIX environment.
With buffering:
f, err := os.Create("/tmp/test.txt")
if err != nil {
panic(err)
}
defer f.Close()
w := bufio.NewWriter(f)
w.WriteString("some text!\n")
w.Flush()
No comments:
Post a Comment