码迷,mamicode.com
首页 > 其他好文 > 详细

golang 文件操作

时间:2019-02-02 23:04:45      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:path   append   lang   同步   返回   err   golang   std   dir   

golang中对文件的操作方法封装在os包中的type File struct中

File represents an open file descriptor.

创建新文件

Create

func Create(name string) (file *File, err error)

Create creates the named file, truncating it if it already exists.
If successful, methods on the returned File can be used for I/O;
If there is an error, it will be of type *PathError.

  1. 不会自动创建父目录,如果要创建的文件父目录不存在会出错
  2. 文件已存在的情况下会覆盖,相当于删掉原来的,再建一个新的
    file,err := os.Create("C:/Users/markz/GO_PROJECT/src/xfile/mm.txt")
    defer file.Close()
    if err != nil {
        fmt.Println(err)
    }
    // file.WriteString("descriptor")

NewFile

func NewFile(fd uintptr, name string) *File 根据文件描述符和名字创建一个新的文件

创建标准输入、输出、错误

     Stdout := os.NewFile(uintptr(syscall.Stdout), "/dev/stdout")
     Stdout.WriteString("hello console can you hear me?")
     defer Stdout.Close()
     // Stdin  := os.NewFile(uintptr(syscall.Stdin), "/dev/stdin")
     // Stderr := os.NewFile(uintptr(syscall.Stderr), "/dev/stderr")

OpenFile

func OpenFile(name string, flag int, perm FileMode) (file *File, err error)

OpenFile is the generalized open call; most users will use Open or Create instead.
It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable.

以多种模式打开文件,其中O_CREATE模式能够创建文件
flag 可以组合使用 O_RDONLY|O_WRONLY
fileMode r=4 w=2 x=1 0666 读写 0777 读写执行

func main(){
    // flag = os.O_CREATE 文件不存在就创建 存在会覆盖  0666 新建的文件具有读写权限
    // file,err := os.OpenFile("sm.txt", os.O_CREATE,0666)

    // flag os.O_RDWR  读写方式打开 文件内容被覆盖  不创建文件  filemode可以为0
    // file,err := os.OpenFile("sm.txt", os.O_RDWR,0)

    //  O_APPEND 最加模式打开文件
    file,err := os.OpenFile("sm.txt", os.O_APPEND,0)

    defer file.Close()
    if err != nil {
        fmt.Println(err)
    }

    file.WriteString(time.Now().Format("2006 01 02 15:04:05"))


}

O_RDONLY:只读模式(read-only)
O_WRONLY:只写模式(write-only)
O_RDWR:读写模式(read-write)
O_APPEND:追加模式(append)
O_CREATE:文件不存在就创建(create a new file if none exists.)
O_EXCL:与 O_CREATE 一起用,构成一个新建文件的功能,它要求文件必须不存在(used with O_CREATE, file must not exist)
O_SYNC:同步方式打开,即不使用缓存,直接写入硬盘
O_TRUNC:打开并清空文件
至于操作权限perm,除非创建文件时才需要指定,不需要创建新文件时可以将其设定为0.虽然go语言给perm权限设定了很多的常量,但是习惯上也可以直接使用数字,如0666(具体含义和Unix系统的一致).
0666 读写权限

打开文件

Open

func Open(name string) (file *File, err error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading;
the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

只读模式打开文件,相当于OpenFile(name string, os.O_RDONLY,0)

读文件

Read

ioutil.ReadFile

不用打开和关闭文件,直接一次读取整个文件内容,返回一个[]byte
文件较大时不推荐使用
逆操作 ioutil.WriteFile

io包还有一个文件拷贝方法io.Copy()

使用bufio

NewReader
func NewReader(rd io.Reader) *Reader 将File包装成*Reader

NewReader returns a new Reader whose buffer has the default size.

ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.
ReadLine() (line []byte, isPrefix bool, err error)
ReadLine tries to return a single line, not including the end-of-line bytes

写文件

Write

func (f *File) Write(b []byte) (n int, err error)

Write writes len(b) bytes to the File. It returns the number of bytes written and an error, if any.
Write returns a non-nil error when n != len(b).

WriteString

func (f *File) WriteString(s string) (ret int, err error) 以字符串形式写入

WriteString is like Write, but writes the contents of string s rather than an array of bytes.

使用bufio

wirter := bufio.NewWriter(file)

writer.WriteString(str) // 内容写到缓存
 
writer.Flush()  // 将缓存数据写入文件

文件夹的操作

os包中
创建和删除Mkdir MkdirAll Remove RemoveAll
文件rename
Rename(oldname,newname string)error

其他

文件路径的操作

在filepath包,主要有join split ext isabs dir abs

判断文件是否存在

os.Stat() 根据返回错误判断
err ==nil 文件或文件夹存在
os.IsNotExist(err) -> true 文件或文件夹不存在
else 不确定是否存在

func PathExists(fpath string) (bool,error){
    _,err := os.Stat(fpath)

    if err == nil{
        // 没有错误 说明文件或文件夹已经存在
        return true, nil
    }

    if os.IsNotExist(err){
        // 不存在
        return false,nil
    }
    return false,errors.New("未知错误")
}

判断是文件还是文件夹

os.Stat(file) 根据返回的fileinfo来判断
fileino.IsDir() -> true 是文件夹 else 是文件

golang 文件操作

标签:path   append   lang   同步   返回   err   golang   std   dir   

原文地址:https://www.cnblogs.com/endurance9/p/10349278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!