当前位置:网站首页>File read write

File read write

2022-07-04 21:51:00 Jimmy_ jimi

Go Linguistic os There is a OpenFile function , The prototype is shown below :
func OpenFile(name string, flag int, perm FileMode) (file *File, err error)

  • O_RDONLY: Open file in read-only mode ;

  • O_WRONLY: Write only mode open file ;

  • O_RDWR: Open file in read-write mode ;

  • O_APPEND: Attach data to the end of the file when writing ( Additional );

  • O_CREATE: If it doesn't exist, a new file will be created ;

  • O_EXCL: and O_CREATE In combination with , The file must not exist , Otherwise an error is returned ;

  • O_SYNC: When doing a series of write operations , Every time I have to wait for the last time I/O When the operation is finished, proceed ;

  • O_TRUNC: If possible , Empty file on open .

example

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    
    // Create a new file , Write content  5  sentence  “http://c.biancheng.net/golang/”
    filePath := "e:/code/golang.txt"
    file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	// Open an existing file , Add content to the original content 
 	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
    if err != nil {
    
        fmt.Println(" File opening failure ", err)
    }
	// Read the contents of the original file , And it's displayed on the terminal 
    reader := bufio.NewReader(file)
    for {
    
        str, err := reader.ReadString('\n')
        if err == io.EOF {
    
            break
        }
        fmt.Print(str)
    }
    // Shut down in time file Handle 
    defer file.Close()
    // When writing a file , Use cached  *Writer
    write := bufio.NewWriter(file)
    for i := 0; i < 5; i++ {
    
        write.WriteString("http://c.biancheng.net/golang/ \n")
    }
    //Flush Write the cached file to the file 
    write.Flush()
}
原网站

版权声明
本文为[Jimmy_ jimi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042059070008.html