file 操作接口函数
- 1.Create函数
功能:
创建一个文件,文件的mode为0666(读写权限),如果文件已存在,则重新创建一个,原文件被覆盖(内容会被清空),
创建的新文件具有读写权限,实现是调用OpenFile来创建文件的。
func Create(name string) (*File, error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
- 2.NewFile函数
功能:根据文件描述符和名字创建一个新的文件
func NewFile(fd uintptr, name string) *File
Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
- 3.OpenFile函数
功能:按指定文件权限和打开方式打开文件或者创建文件,其中flag标志如下
func OpenFile(name string, flag int, perm FileMode) (*File, error)
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系统的一致).
-
4.Open函数
功能:
打开一个文件,返回文件描述符,该文件描述符只有只读权限.
他相当于OpenFile(name string,O_RDWR,0)
func Open(name string) (*File, error) -
5.Pipe函数
功能:
返回一对连接的文件,从r中读取写入w中的数据,即首先向w中写入数据,
此时从r中变能够读取到写入w中的数据,Pipe()函数返回文件和该过程中产生的错误.
func Pipe() (r *File, w *File, err error)
- 6.Close方法
func (f *File) Close() error
功能:
关闭文件,使其不能够再进行i/o操作,其经常和defer一起使用,用在创建或者打开某个文件之后,
这样在程序退出前变能够自己关闭响应的已经打开的文件。
- 7.Read方法
func (f *File) Read(b []byte) (n int, err error)
功能:
读取文件中的内容到b中,n是读取的字节数
如果len(b) 大于文件中可读的字节数,则可以读取文件的全部内容,n是文件中的字节数
如果len(b)小于文件中可读的字节数,则只读取文件中的前len(b)个字节(即把len(b)个字节从f中读取到b中)。
- 8.ReadAt方法
func (f *File) ReadAt(b []byte, off int64) (n int, err error)
功能:
和Read类似,不过ReadAt指定开始读取的位置offset
- 9.Seek方法
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
功能:
Seek设置下一个读或写操作的偏移量offset,根据whence来解析,whence可以理解为参考标准,
0意味着相对于文件的原始位置,1意味着相对于当前偏移量,2意味着相对于文件结尾。
它返回新的偏移量和错误(如果存在)。whence的定义如下(io包下)
const (
SeekStart = 0 // seek relative to the origin of the file
SeekCurrent = 1 // seek relative to the current offset
SeekEnd = 2 // seek relative to the end
)
-
- Write方法
func (f *File) Write(b []byte) (n int, err error)
功能:
将b中的数据写入f文件
-
- WriteAt方法
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
功能:
将b中数据写入f文件中,写入时从offset位置开始进行写入操作
-
- WriteString方法
func (f *File) WriteString(s string) (ret int, err error)
功能:
将字符串s写入文件中
实例 1 文件读写
package main
import (
"os"
"io"
"fmt"
)
func test(){
file,_ := os.OpenFile("readme.md", os.O_RDWR|os.O_CREATE,0666)
file.Write([]byte("hello world\n"))
file.WriteString("append readme context $ % \n")
file.WriteString("\n")
file.WriteString("\n")
file.WriteString("\n")
file.WriteString("\n")
file.WriteString("--end--\n")
file.Seek(0,io.SeekStart)
file.Write([]byte("write start\n"))
file.Seek(0,io.SeekStart)
b := make([]byte,1024)
n,err := file.Read(b)
if err != nil {
fmt.Println("read file err:",err)
return
}
file.Close()
fmt.Printf("file size:%d context:\n\r%s\n",n,string(b[:n]))
}
func main() {
test()
}
运行结果
robot@ubuntu:~/gomod/src/file$ go run fileRW.go
file size:51 context:
write start
append readme context $ %
--end--
文件路径接口
-
- Getwd函数
func Getwd() (dir string, err error)
功能:获取当前目录,类似linux中的pwd。
-
- Chdir函数
func Chdir(dir string) error
功能:
将当前工作目录更改为dir目录。
-
- Mkdir函数
func Mkdir(name string, perm FileMode) error
功能:
用于创建指定权限的文件夹,只能创建一级目录。
注意:当该文件夹已经存在时,会返回error(Cannot create a file when that file already exists.)
-
- MkdirAll函数
func MkdirAll(path string, perm FileMode) error
功能:
用于递归创建文件目录,可以创建多级目录。
-
- Readdir 方法
func (f *File) Readdir(n int) ([]FileInfo, error)
功能:
读取指定目录f下的所有内容,如果f是文件,则会返回The system cannot find the file specified.的错误。
当n> 0, Readdir返回最多n个FileInfo结构。
当n <= 0,Readdir返回该目录下所有文件或目录的FileInfo信息。
-
- Readdirnames方法
func (f *File) Readdirnames(n int) (names []string, err error)
功能:
读取并返回目录f里面的文件(或文件夹)的名称列表
如果n>0,Readdirnames返回最多n个名字。
如果n<0,Readdirnames返回目录下所有的文件的名字,用一个切片表示。
-
- IsExist函数
func IsExist(err error) bool
功能:
返回一个布尔值,它指明err错误是否报告了一个文件或者目录已经存在。
它被ErrExist和其它系统调用满足。
-
- IsNotExist函数
func IsNotExist(err error) bool
功能:
返回一个布尔值,它指明err错误是否报告了一个文件或者目录不存在。
它被ErrNotExist 和其它系统调用满足。
-
- IsPermission函数
func IsPermission(err error) bool
功能:
判定err错误是否是权限错误。它被ErrPermission 和其它系统调用满足。
文件权限接口
-
- Chmod函数
func Chmod(name string, mode FileMode) error
功能:
更改文件的权限(读写执行,分为三类:all-group-owner)
-
- Chown函数
func Chown(name string, uid, gid int) error
功能:
更改文件拥有者owner
-
- Chtimes函数
func Chtimes(name string, atime time.Time, mtime time.Time) error
功能:
更改文件的访问时间和修改时间,atime表示访问时间,mtime表示更改时间
链接文件接口
-
- Lchown函数
func Lchown(name string, uid, gid int) error
功能:
改变了文件的gid和uid。如果文件是一个符号链接,它改变的链接自己。
如果出错,则会是*PathError类型。
-
- Link函数
func Link(oldname, newname string) error
功能:
创建一个从oldname指向newname的硬连接,对一个进行操作,则另外一个也会被修改。
注意:newname必须是不存在的,负责会返回error(Cannot create a file when that file already exists.)
-
- Readlink函数
func Readlink(name string) (string, error)
功能:
返回符号链接的目标。如果出错,将会是 *PathError类型。
-
- Symlink函数
func Symlink(oldname, newname string) error
功能:
创建一个newname作为oldname的符号连接,这是一个符号连接(软连接),与Link的硬连接不同,
利用Link创建的硬连接,则newname和oldname的file互不影响,一个文件删除,另外一个文件不受影响;
但是利用SymLink创建的符号连接,其newname只是一个指向oldname文件的符号连接,当oldname file删除之后,
则newname的文件也就不能够继续使用。
文件删除
-
- Remove函数
func Remove(name string) error
功能:
用于删除文件或目录(该文件或目录只能是最后一级)
比如说: /home/test/aaa/ccc,只能删除最后一级ccc目录,
不能直接删除aaa的目录,如果需要删除多级目录,则使用RemoveAll函数。
- RemoveAll函数
func RemoveAll(path string) error
功能:
用于删除目录及它包含的所有子目录和文件。
文件属性接口
type FileInfo interface {
Name() string // base name of the file 文件名称
Size() int64 // length in bytes for regular files; system-dependent for others 文件大小
Mode() FileMode // file mode bits 文件权限
ModTime() time.Time // modification time 文件更改时间
IsDir() bool // abbreviation for Mode().IsDir() 文件是否为目录
Sys() interface{
} // underlying data source (can return nil) 基础数据源
}
FileInfo用来描述一个文件的相关信息,当调用Stat和Lstat函数时,会获取到该文件信息FileInfo。
- 1.Stat函数
func Stat(name string) (FileInfo, error)
功能:
返回描述文件的FileInfo信息。如果出错,将是 *PathError类型。
-
- Lstat函数
func Lstat(name string) (FileInfo, error)
功能:
返回描述文件的FileInfo信息。如果文件是符号链接,返回的FileInfo描述的符号链接。
Lstat不会试着去追溯link。如果出错,将是 *PathError类型。
-
- IsDir方法
func (m FileMode) IsDir() bool
功能:
判断m是否是目录,也就是检查文件是否有设置的ModeDir位
-
- IsRegular方法
func (m FileMode) IsRegular() bool
功能:
判断m是否是普通文件,也就是说检查m中是否有设置mode type
-
- Perm方法
func (m FileMode) Perm() FileMode
功能:
返回m的权限位
- 6.String方法
func (m FileMode) String() string
功能:
返回m的字符串表示
package main
import (
"os"
"io"
"fmt"
)
func fstat(){
s,err := os.Stat("readme.md")
if err != nil {
fmt.Printf("stat err:",err)
return
}
fmt.Printf("name:%s,size:%d\n",s.Name(),s.Size())
ls, e := os.Lstat("readme.md")
if e != nil {
fmt.Printf("stat err:",e)
return
}
fmt.Printf("name:%s,size:%d\n",ls.Name(),ls.Size())
}
func main() {
fstat()
}
运行结果
robot@ubuntu:~/gomod/src/file$ go run fileRW.go
name:readme.md,size:51
name:readme.md,size:51
文件其他接口
- 1.Name方法
func (f *File) Name() string
功能:
返回文件名字,与file.Stat().Name()等价
-
- Rename函数
func Rename(oldpath, newpath string) error
功能:
用于修改文件夹或文件名的名称
-
- Fd方法
func (file *File) Fd() uintptr
功能:
返回系统文件描述符,也叫做文件句柄。
-
- Sync方法
func (f *File) Sync() (err error)
功能:
同步操作,将当前存在内存中的文件内容写入硬盘。
-
- Truncate方法
func (f *File) Truncate(size int64) error
功能:
类似 os.Truncate(name, size),将文件进行截断。
参考链接:
golang 内置包官方接口文档