当前位置:网站首页>Golang write file code example

Golang write file code example

2022-06-23 16:24:00 Learn programming notes

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)

among name Is the file name of the file , If you are not running under the current path, you need to add a specific path ;flag Is the processing parameter of the file , by int type , The specific values may vary depending on the system , But the effect is the same .

Here are some common flag File processing parameters : 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 1】: Create a new file golang.txt, And write in it 5 sentence “http://c.biancheng.net/golang/”

  • Case study 1.go

1.go

package main

import (

"bufio"

"fmt"

"os"

)

func main() {
    

// Create a new file , Write content  5  sentence  “http://c.biancheng.net/golang/”

filePath := "D:/goLang/github/code/golang.txt"

file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)

if err != nil {
    

fmt.Println(" File opening failure ", err)

}

// Shut down in time file Handle 

defer file.Close()

// When writing a file , Use cached  *Writer

/* func NewWriter func NewWriter(w io.Writer) *Writer NewWriter Create a buffer with a default size 、 write in w Of *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()

}
原网站

版权声明
本文为[Learn programming notes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231538134847.html