文件操作详解
1. 文件关闭操作
使用 fclose 函数关闭文件流:
c
int fclose(FILE *stream);
- 参数 :
stream为需要操作的文件流指针 - 作用 :释放
fopen申请的系统资源 - 返回值 :成功返回
0,失败返回EOF
2. 缓冲机制
(1) 行缓冲(1024字节)
适用于终端交互(如 stdout),刷新条件:
- 遇到换行符
\n - 缓冲区满(1024字节)
- 程序正常结束
- 主动调用
fflush(stdout)
c
printf("aaa");
fflush(stdout); // 强制刷新
(2) 全缓冲(4096字节)
适用于普通文件操作,刷新条件:
- 缓冲区满(4096字节)
- 程序结束
- 主动调用
fflush(fp)
c
fputs("hello", fp);
fflush(fp); // 强制刷新
(3) 无缓冲
适用于错误处理(如 stderr):
- 数据直接输出,不缓存
c
fprintf(stderr, "fopen error %s", filename);
3. 文件定位函数
c
int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
fseek参数 :whence:起始位置(SEEK_SET/SEEK_CUR/SEEK_END)offset:正数向文件末尾偏移,负数向文件开头偏移
ftell:返回当前指针距离开头的字节数rewind:复位指针到文件开头
4. 文件IO与标准IO对比
| 特性 | 标准IO | 文件IO |
|---|---|---|
| 访问资源 | FILE* 文件流指针 |
int 文件描述符 |
| 缓存机制 | 带缓冲区(适合普通文件) | 无缓冲区(适合设备文件) |
| 操作函数 | fopen/fclose |
open/close |
5. 文件操作步骤
- 打开文件:
c
int open(const char *pathname, int flags, int mode);
flags:O_RDONLY/O_WRONLY/O_RDWR/O_CREAT/O_TRUNC/O_APPEND
- 读写操作:
c
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
- 关闭文件:
c
int close(int fd);