http://blog.chinaunix.net/uid-24774106-id-3993609.html
操作文件是任何编程语言都绕不过,要掌握一门语言,知道如何操作文件是必不可少的,今天学习了下golang对文件操作的支持。
golang对文件的支持是在os package里。我无意将本文写成官方文档的模样,我只是想讨论如何利用这些接口操作文件。
OPEN
熟悉文件系统的人都知道,open是整个文件系统中最复杂的接口之一。熟悉C语言的都知道,C语言中有open和creat,接口如下:
- #include<sys/types.h>
- #<sys/stat>
- #<fcntl>
-
- intopen(const char*pathname,intflags);
- ;
-
- intcreat)
O_RDONLY
O_WRONLY
O_RDWR
O_DIRECT
O_APPEND
O_TRUNC
。。。。
funcOpenFile(namestringint(file*File)
我们看到了也有flag,也有FileMode.比如说我要读写打开一个文件,如果不存在就创建,如果存在,就追加写,如何写go 代码?
f:=os."test.txt".O_CREATE|os.O_APPEND.O_RDWR)
if(err!=nil{
panicerr)
}
我们看到了,golang中也有这些标志(注意O_CREATE,在C语言中,是O_CREAT),我在上面代码片段中用了几个标志
const(
O_RDONLY=syscall.O_RDONLY // open the file read-only.
O_WRONLY.O_WRONLY // open the file write.
O_RDWR.O_RDWR // open the file read-write.
O_APPEND.O_APPEND // append data to the file when writing.
O_CREATE.O_CREAT // create a new fileifnone exists.
O_EXCL.O_EXCL // used with O_CREATEnotexist
O_SYNC.O_SYNC // openforsynchronous I/O.
O_TRUNC.O_TRUNC //ifpossible)
C语言中有creat,没有则创建,有则截断写,本质等于O_WRONLY | O_CREAT | O_TRUNC
@H_404_267@>