【C语言进阶】文件操作(二)
1、文件随机读写
1.1、fseek函数
fseek函数的作用,根据文件指针的位置和偏移量来定位文件指针
随机读文件
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE* pf = fopen("text.txt", "r"); if (pf == NULL) { printf("%s ", strerror(errno)); } //读文件 int ch = fgetc(pf); printf("%c ", ch); ch = fgetc(pf); printf("%c ", ch); //定位文件指针 //fseek(pf, 1, SEEK_CUR);//三个参数(流、偏移量、文件指针位置) //fseek(pf, 3, SEEK_SET); fseek(pf, -1, SEEK_END); ch = fgetc(pf); printf("%c ", ch); fclose(pf); pf = NULL; return 0; }
随机写文件
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE* pf = fopen("text.txt", "w"); if (pf == NULL) { printf("%s ", strerror(errno)); } //写文件 int ch = 0; for (ch = a; ch <= z; ch++) { fputc(ch, pf); } //定位文件指针 fseek(pf, -1, SEEK_END);//可以在指定位置修改你写入的内容 fputc(#, pf); fclose(pf); pf = NULL; return 0; }
1.2、ftell函数
ftell函数的作用是告诉你当前文件指针的偏移量(告诉你当前文件指针位置)
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE* pf = fopen("text.txt", "r"); if (pf == NULL) { printf("%s ", strerror(errno)); } //读文件 int ch = fgetc(pf); printf("%c ", ch); ch = fgetc(pf); printf("%c ", ch); int ret = ftell(pf); printf("%d ", ret); fclose(pf); pf = NULL; return 0; }
1.3、rewind函数
rewind函数的作用是把文件指针偏移量置为 0,文件指针重新指向文件开头
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE* pf = fopen("text.txt", "r"); if (pf == NULL) { printf("%s ", strerror(errno)); } //读文件 int ch = fgetc(pf); printf("%c ", ch); ch = fgetc(pf); printf("%c ", ch); int ret = ftell(pf); printf("%d ", ret); rewind(pf); ret = ftell(pf); printf("%d ", ret); fclose(pf); pf = NULL; return 0; }
2、判断文件读取是否结束
1、文本文件读取是否结束 判断返回值是否为EOF(fgetc)或者NULL(fgets)
例如: fgetc判断是否为EOF; fgets判断返回值是否为NULL;
2、二进制文件读取结束判断,判断返回值是否小于实际要读取的个数
例如: fread判断返回值是否小于实际要读的个数
3、文件缓冲区
文件在储存的时候,会先将数据储存在缓冲区中,缓冲区存满之后,一次性写入文件中
文件读出数据时也是一样,会先将数据储存在缓冲区中,缓冲区存满之后,一次性读出来
只要你关闭文件,就会刷新缓冲区