GoLang操作文件的方法有很多,这里记录和归纳一下。主要有create/NewFile/Open/OpenFile/Pipe这5个。
- func Create(name string) (file *File,err error)
- func NewFile(fd uintptr,name string) *File
- func Open(name string) (file *File,err error)
- func OpenFile(name string,flag int,perm FileMode) (file *File,err error)
- func Pipe() (r *File,w *File,err error)
Create方法是默认创建一个权限是0666的空文件,如果文件已经存在就清空它。如果运行成功,就返回一个可以做I/O操作的文件,他的权限是O_RDWR。如果错误,就返回*PathError.
Open打开该文件用于读取,如果成功,返回一个用于读取的文件,文件权限是O_RDONLY。如果错误,就返回*PathError。
OpenFile是一个广义的调用,大部分的用户使用Create或者Open方法。可以按照指定的flag和perm去打开文件。成功返回一个可用于I/O的文件,错误就返回*PathError。
Pipe返回一对连接文件,从r读取,返回bytes写到w。
另外:
- const (
- O_RDONLY int = syscall.O_RDONLY // open the file read-only.
- O_WRONLY int = syscall.O_WRONLY // open the file write-only.
- O_RDWR int = syscall.O_RDWR // open the file read-write.
- O_APPEND int = syscall.O_APPEND // append data to the file when writing.
- O_CREATE int = syscall.O_CREAT // create a new file if none exists.
- O_EXCL int = syscall.O_EXCL // used with O_CREATE,file must not exist
- O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
- O_TRUNC int = syscall.O_TRUNC // if possible,truncate file when opened.
- )
- //读取文件
- package main
- import(
- "os"
- "fmt"
- "flag"
- )
- func main(){
- flag.Parse()
- file := flag.Arg(0)
- f,err := os.Open(file)
- if err != nil{
- panic(err)
- }
- defer f.Close()
- buf := make([]byte,100)
- for{
- rint,_ := f.Read(buf)
- if 0==rint{break}
- fmt.Println(string(buf[:rint]))
- //os.Stdout.Write(buf[:rint])
- }
- }
- //使用bufio读取
- package main
- import(
- "os"
- "bufio"
- "fmt"
- "flag"
- )
- func main(){
- flag.Parse()
- file := flag.Arg(0)
- f,err := os.Open(file)
- if err != nil{
- panic(err)
- }
- defer f.Close()
- br :=bufio.NewReader(f)
- /*
- buffer := bytes.NewBuffer(make([]byte,1024))
- for{
- if part,prefix,err1 := br.ReadLine(); err1!=nil{
- break
- }
- buffer.Write(part)
- if !prefix{
- lines = append(lines,buffer.String())
- buffer.Reset()
- }
- }
- fmt.Println(lines)
- */
- for {
- line,err1:=br.ReadString("\n")
- if err == os.EOF{
- break
- }else{
- fmt.Printf("%v",line)
- }
- }
- }