Go os and bufio
The os and bufio packages are extremely important in the Go language, primarily used for handling file systems and I/O operations.
os package
The os package provides basic functionalities for interacting with the operating system, including file operations, environment variables, system calls, and more.
Standard Input/Output in the os Package
The terminal is essentially a file, hence it possesses relevant file operation functionalities:
- os.Stdin:An instance of the file for standard input
- os.Stdout:An instance of the file for standard output
- os.Stderr:An instance of the file for standard error output
buf := make([]byte, 1024)
os.Stdin.Read(buf)
os.Stdout.WriteString(string(buf))
File Operations in the os Package
FileMode | Meaning |
os.O_CREATE | Create a file |
os.O_RDONLY | Read-only |
os.O_WRONLY | Write-only |
os.O_RDWR | Read and write |
os.O_TRUNC | Clear file content |
os.O_APPEND | Append content |
There are numerous interfaces related to file operations, but the commonly used ones are:
- func Open(name string) (*File, error),Opens a file in read-only mode
- func Create(name string) (*File, error),Creates a file for reading and writing. If the file already exists, it is truncated
- func OpenFile(name string, flag int, perm FileMode),Opens or creates a file with specified flags and permissions
- func (f *File) Read(b []byte) (n int, err error),Reads file content into the slice b
- func (f *File) Write(b []byte) (n int, err error),Writes the slice b into the file
- func (f *File) WriteString(s string) (n int, err error),Writes the string s into the file
fileOpen, err := os.Open("/tmp/log.txt")
if err != nil {
fmt.Println("open file failed!, err:", err)
return
}
defer fileOpen.Close()
buf := make([]byte, 1024)
content := []byte{}
for {
n, err := fileOpen.Read(buf)
if (err != nil) || (err == io.EOF) {
break
}
content = append(content, buf[:n]...)
}
fileCreate, err := os.Create("/tmp/restore.txt")
if err != nil {
fmt.Println("failed to create file: %v", err)
return
}
/*
//If you want to append content
fileCreate, err := os.OpenFile("/tmp/restore.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatalf("failed to open file: %v", err)
}
*/
defer fileCreate.Close()
if len(content) > 0 {
fileCreate.Write(content)
//fileCreate.WriteString(string(content))
}
Directory Operations in the os Package
There are also several interfaces related to directory operations, commonly used ones include:
- func Getwd() (dir string, err error),Retrieves the current working directory
- func IsNotExist(err error) bool,Determines if an error indicates that a file or directory does not exist
- func IsExist(err error),Determines if an error indicates that a file or directory already exists
- func MkdirAll(path string, perm FileMode),Creates a directory along with all necessary parent directories
- func Mkdir(name string, perm FileMode),Creates a new directory
//If the directory does not exist, it will be created
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0777)
if err != nil {
fmt.Printf("failed to create dir '%s':%v", dir, err)
}
fmt.Printf("dir '%s' created success\n", dir)
}
bufio Package
The bufio package implements buffered I/O operations, which are typically faster than unbuffered I/O due to reduced system calls. Some commonly used interfaces include:
- func NewReader(rd io.Reader) *Reader,Creates a new buffered reader
- func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error),Reads a line, excluding "\r\n" or "\n"
- func (b *Reader) ReadString(delim byte) (string, error),Reads characters until a specified delimiter or EOF is encountered
- func NewWriter(w io.Writer) *Writer,Creates a new buffered writer
- func (b *Writer) WriteString(s string) (int, error),Writes a string to the buffer
- func (b *Writer) Flush() error,Flushes the buffer's contents to the file
func main() {
fileOpen, err := os.Open("/tmp/log.txt")
if err != nil {
return
}
defer fileOpen.Close()
var content string
reader := bufio.NewReader(fileOpen)
for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
if err != nil {
break
}
content += string(line) + "\r\n"
}
fileCreate, err := os.Create("/tmp/restore.txt")
if err != nil {
return
}
defer fileCreate.Close()
writer := bufio.NewWriter(fileCreate)
defer writer.Flush()
_, err = writer.WriteString(content)
if err != nil {
return
}
}
Take a break
👉👉👉 【Jade Dynasty EP48】Lu Xueqi expressed her love to Gui Li, and danced a sword dance for him