文件操作总结

来源:互联网 发布:smtp服务器 端口 编辑:程序博客网 时间:2024/05/18 00:36

对于文件的基本操作函数很多,大致可以分为C标准库自带的带缓存的文件操作函数和LINUX下的底层不带缓存的文件操作函数。
1、打开文件

open():打开文件int open(const char *pathname, int flags);int open(const char *pathname, int flags, mode_t mode);fopen():打开文件FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fd, const char *mode);

对于open()函数,打开文件不论是读还是写,都不会清空清空文件的内容,除非以写的方式打开文件并且加了截断的操作,此时就会清空文件内的原有内容。
而对于fopen()函数开说,当以写的方式打开文件就会清空文件的内容,在(函数手册内详细说明了)。
以下说明摘自linux函数手册:
[w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.]

FILE *fdopen(int fd, const char *mode);int fileno(FILE *stream);

以上一组函数用于文件描述符和文件指针的转换。
2、读文件

ssize_t read(int fd, void *buf, size_t count);size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

3、写文件

size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);ssize_t write(int fd, const void *buf, size_t count);

4、关闭文件

int close(int fd);int fclose(FILE *fp);

5、定位文件内容

off_t lseek(int fd, off_t offset, int whence);int fseek(FILE *stream, long offset, int whence);

对于以上的文件的操作函数,我们只需要记住他们的不同之处,和使用的细节,关于具体的函数参数和返回值,在linux手册中都有详细的说明[man 函数名]就会详细的说明,有的函数还带有例子说明。

0 0
原创粉丝点击