文件
涉及到了数据持久化的问题,我们一般数据持久化的方法有,把数据存放在磁盘文件、存放到数据库等方式。
使用文件我们可以将数据直接存放在电脑的硬盘上,做到了数据的持久化。
磁盘上的文件是文件。
但是在程序设计中,我们一般谈的文件有两种:程序文件、数据文件(从文件功能的角度来分类的)。
程序文件
包括源程序文件(后缀为.c),目标文件(windows环境后缀为.obj),可执行程序(windows环境后缀为.exe)。
数据文件
文件的内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读取数据的文件,或者输出内容的文件。
我们本篇博客讨论的是数据文件。在以前各章所处理数据的输入输出都是以终端为对象的,即从终端的键盘输入数据,运行结果显示到显示器上。其实有时候我们会把信息输出到磁盘上,当需要的时候再从磁盘上把数据读取到内存中使用,这里处理的就是磁盘上文件。
文件名
一个文件要有一个唯一的文件标识,以便用户识别和引用。
文件名包含3部分:文件路径+文件名主干+文件后缀
例如: c:\code\test.txt
为了方便起见,文件标识常被称为文件名。
文件的打开和关闭
文件指针
缓冲文件系统中,关键的概念是“文件类型指针”,简称“文件指针”。
每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名
字,文件状态及文件当前的位置等)。这些信息是保存在一个结构体变量中的。该结构体类型是有系统
声明的,取名FILE.
例如,VS2013编译环境提供的 stdio.h 头文件中有以下的文件类型申明:
struct _iobuf char * int char * int int int int char * }; typedef struct
不同的C编译器的FI
每当打开一个文件的时候,系统会根据文件的情况自动创建一个FILE结构的变量,并填充其中的信息,
使用者不必关心细节。
一般都是通过一个FILE的指针来维护这个FILE结构的变量,这样使用起来更加方便
下面我们可以创建一个FILE*的指针变量:
FILE* pf;//文件指针变量
定义pf是一个指向FILE类型数据的指针变量。可以使pf指向某个文件的文件信息区(是一个结构体变量)。通过该文件信息区中的信息就能够访问该文件。也就是说,通过文件指针变量能够找到与它关联的文件。
文件的打开和关闭
- 文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。
- 在编写程序的时候,在打开文件的同时,都会返回一个FILE*的指针变量指向该文件,也相当于建立了指针和文件的关系。
- ANSIC 规定使用fopen函数来打开文件,fclose来关闭文件
//打开文件 FILE * fopen (const char * filename, const char * mode) //关闭文件 int fclose ( FILE * stream ); * filename, const char * mode );
打开方式:
文件使用方式 | 含义 | 如果指定文件不存在 |
“r”(只读) | 为了输入数据,打开一个已经存在的文本文件 | 出错 |
“w”(只写) | 为了输出数据,打开一个文本文件 | 建立一个新的文件 |
“a”(追加) | 向文本文件尾添加数据 | 建立一个新的文件 |
“rb”(只读) | 为了输入数据,打开一个二进制文件 | 出错 |
“wb”(只写) | 为了输出数据,打开一个二进制文件 | 建立一个新的文件 |
“ab”(追加) | 向一个二进制文件尾添加数据 | 出错 |
“r+”(读写) | 为了读和写,打开一个文本文件 | 出错 |
“w+”(读写) | 为了读和写,建议一个新的文件 | 建立一个新的文件 |
“a+”(读写) | 打开一个文件,在文件尾进行读写 | 建立一个新的文件 |
“rb+”(读写) | 为了读和写打开一个二进制文件 | 出错 |
“wb+”(读写) | 为了读和写,新建一个新的二进制文件 | 建立一个新的文件 |
“ab+”(读写) | 打开一个二进制文件,在文件尾进行读和写 | 建立一个新的文件 |
对于fopen和fclose的使用:
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //关闭文件 fclose(pf); pf = NULL; return 0; }
对于No such file or directory,我们可以在目录底下创建test.txt文件(相对路径)解决这个问题。如果想打开桌面的文件,我们打开绝对路径(在属性的位置)!!!记得加上转义字符
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("C:\\Users\\ASUS\\Desktop\\test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //关闭文件 fclose(pf); pf = NULL; return 0; }
文件的顺序读写
功能 | 函数名 | 适用于 |
字符输入函数 | fgetc | 所有输入流 |
字符输出函数 | fputc | 所有输出流 |
文本行输入函数 | fgets | 所有输入流 |
文本行输出函数 | fputs | 所有输出流 |
格式化输入函数 | fscanf | 所有输入流 |
格式化输出函数 | fprintf | 所有输出流 |
二进制输入 | fread | 文件 |
二进制输出 | fwrite | 文件 |
对于这么多的函数,我们必须通过代码来进行练习:
写字符
int fputs ( const char * str, FILE * stream );
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("test.txt", "w"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //写文件 fputc('a', pf); //关文件 fclose(pf); pf = NULL; return 0; }
找到路径查看文件:
读字符
int fgetc ( FILE * stream );
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 int ch = fgetc(pf); printf("%c\n", ch); //关文件 fclose(pf); pf = NULL; return 0; }
返回类型为 int
以适应特殊值 EOF,这表示失败.基于此,我们可以循环输出:
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 int ch = 0; while ((ch = fgetc(pf))!= EOF) { printf("%c ",ch); } //关文件 fclose(pf); pf = NULL; return 0; }
写一行数据
int fputs ( const char * str, FILE * stream );
#include <stdio.h> #include <errno.h> //写一行数据 int main() { FILE* pf = fopen("test.txt", "w"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //写一行数据 fputs("hello", pf); fclose(pf); pf = NULL; return 0; }
打开当前目录下:
我们发现之前的内容没有了,对于fputs而言,会情况之前的内容。如果想保留之前内容的话,我们可以用"a"追加来进行相关操作:
#include <stdio.h> #include <errno.h> int main() { FILE* pf = fopen("test.txt", "a"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //写一行数据 fputs("hello", pf); fclose(pf); pf = NULL; return 0; }
再次打开:
对于数据没有换行,我们可以自己加个\n即可
读一行数据
char * fgets ( char * str, int num, FILE * stream );
#include <stdio.h> #include <errno.h> //读一行数据 int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读一行数据 char arr[20]; fgets(arr,5,pf); printf("%s\n", arr); fclose(pf); pf = NULL; return 0; }
读5个数据,真正读到的才4个,还有一个’\0’!!!
当然,对于报错的信息strerror我们可以用perror来替换(这里为了演示效果,我把test.txt文件删除了)
#include <stdio.h> #include <errno.h> //读一行数据 int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { //printf("%s\n", strerror(errno)); perror("fopen"); return 1; } //读一行数据 char arr[20]; fgets(arr,5,pf); printf("%s\n", arr); fclose(pf); pf = NULL; return 0; }
格式化输出
int fprintf ( FILE * stream, const char * format, ... );
struct S { char arr[10]; int age; float score; }; int main() { struct S s = { "zhangsan",25,50.5f }; FILE* pf = fopen("test.txt", "w"); if (pf == NULL) { perror("fopen"); } fprintf(pf,"%s %d %f", s.arr, s.age, s.score); fclose(pf); pf = NULL; return 0; }
打开目录底下的文件:
格式化输入
int fscanf ( FILE * stream, const char * format, ... );
struct S { char arr[10]; int age; float score; }; int main() { struct S s = {0}; FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { perror("fopen"); } fscanf(pf, "%s %d %f", s.arr, &(s.age), &(s.score)); printf("%s %d %f\n",s.arr,s.age,s.score); fclose(pf); pf = NULL; return 0; }
这里有人会说了,那用fprintf打印到屏幕上去呢?
struct S { char arr[10]; int age; float score; }; int main() { struct S s = {0}; FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { perror("fopen"); } fscanf(pf, "%s %d %f", s.arr, &(s.age), &(s.score)); fprintf(stdout,"%s %d %f\n",s.arr,s.age,s.score); fclose(pf); pf = NULL; return 0; }
至此,前面我们学的函数都是文本,那对于二进制的呢👇
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
struct S { char arr[10]; int age; float score; }; int main() { struct S s = { "zhangsan",25,50.5f }; //以二进制形式写到文件中 FILE* pf = fopen("test.txt", "w"); if (pf == NULL) { perror("fopen"); return 1; } //二进制的方式写 fwrite(&s, sizeof(struct S), 1, pf); fclose(pf); pf = NULL; }
打开目录底下的文件:
struct S { char arr[10]; int age; float score; }; int main() { struct S s = {0}; //以二进制形式写到文件中 FILE* pf = fopen("test.txt", "rb"); if (pf == NULL) { perror("fopen"); return 1; } //二进制的方式读 fread(&s, sizeof(struct S), 1, pf); printf("%s %d %f", s.arr, s.age, s.score); fclose(pf); pf = NULL; }
scanf:是针对标准输入的格式化输入语句
printf:是针对标准输出的格式化输出语句
fscanf:是针对所有输入流的格式化输入语句
fprintf:是针对所有输出流的格式化输出语句
sscanf:从一个字符串中转化成一个格式化的数据
int sscanf ( const char * s, const char * format, ...);
sprintf:把一个格式化的数据写到字符串中,本质是把一个格式化的数据转换成字符串
int sprintf ( char * str, const char * format, ... );
struct S { char arr[10]; int age; float score; }; int main() { struct S s = { "zhangsan",20,55.5f }; char buf[100] = { 0 }; sprintf(buf,"%s %d %f", s.arr, s.age, s.score); printf("%s\n", buf); return 0; }
struct S { char arr[10]; int age; float score; }; int main() { struct S s = { "zhangsan",20,55.5f }; struct S tmp = { 0 }; char buf[100] = { 0 }; sprintf(buf,"%s %d %f", s.arr, s.age, s.score); printf("%s\n", buf); //从字符串buf中获取一个格式化的数据到tmp中 sscanf(buf,"%s %d %f", tmp.arr, &(tmp.age), &(tmp.score)); printf("格式化:%s %d %f\n", tmp.arr, tmp.age, tmp.score); return 0; }
文件的随机读写
前面的函数都有一个特点,那就是只能根据顺序去进行读写。下面我们来看看一些可以进行随机读写的函数
fseek
根据文件指针的位置和偏移量来定位文件指针
int fseek ( FILE * stream, long int offset, int origin );
先来看看我们当前test.txt中的内容是什么:
int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //定位文件指针 fseek(pf,2,SEEK_SET); int ch = fgetc(pf); printf("%c\n", ch); ch = fgetc(pf); printf("%c\n", ch); fclose(pf); pf = NULL; return 0; }
int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //定位文件指针 fseek(pf,2,SEEK_SET); int ch = fgetc(pf); printf("%c\n", ch); fseek(pf, 2, SEEK_CUR); ch = fgetc(pf); printf("%c\n", ch); fclose(pf); pf = NULL; return 0; }
ftell
返回文件指针相对于起始位置的偏移量
long int ftell ( FILE * stream );
int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //定位文件指针 fseek(pf, 2, SEEK_SET); int ch = fgetc(pf); printf("%c\n", ch); printf("%d\n", ftell(pf));//3 //fseek(pf, 2, SEEK_CUR); fseek(pf, -1, SEEK_END); ch = fgetc(pf); printf("%c\n", ch); printf("%d\n", ftell(pf));//6 fclose(pf); pf = NULL; return 0; }
rewind
让文件指针的位置回到文件的起始位置
void rewind ( FILE * stream );
int main() { FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { printf("%s\n", strerror(errno)); return 1; } //读文件 //定位文件指针 fseek(pf, 2, SEEK_SET); int ch = fgetc(pf); printf("%c\n", ch); printf("%d\n", ftell(pf));//3 //fseek(pf, 2, SEEK_CUR); fseek(pf, -1, SEEK_END); ch = fgetc(pf); printf("%c\n", ch); printf("%d\n", ftell(pf));//6 rewind(pf); ch = fgetc(pf); printf("%c\n", ch);//a fclose(pf); pf = NULL; return 0; }
文本文件和二进制文件
根据数据的组织形式,数据文件被称为文本文件或者二进制文件。
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件。
一个数据在内存中是怎么存储的呢?
字符一律以ASCII形式存储,数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。
如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而
二进制形式输出,则在磁盘上只占4个字节
测试代码:
#include <stdio.h> int main() { int a = 10000; FILE* pf = fopen("test.txt", "wb"); fwrite(&a, 4, 1, pf);//二进制的形式写到文件中 fclose(pf); pf = NULL; return 0; }
打开文件发现看不懂:
我们可以通过VS进行二进制编辑器打开方式:
文件读取结束的判定
牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束
- **文本文件读取是否结束,判断返回值是否为 EOF ( fgetc ),或者 NULL ( fgets )**例如:
fgetc 判断是否为 EOF .
fgets 判断返回值是否为 NULL - 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。例如:
fread判断返回值是否小于实际要读的个数。
下面,我们举个例子:
文本文件的例子:
#include <stdio.h> #include <stdlib.h> int main(void) { int c; // 注意:int,非char,要求处理EOF FILE* fp = fopen("test.txt", "r"); if(!fp) { perror("File opening failed"); return EXIT_FAILURE; } //fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF while ((c = fgetc(fp)) != EOF) // 标准C I/O读取文件循环 { putchar(c); } //判断是什么原因结束的 if (ferror(fp)) puts("I/O error when reading"); else if (feof(fp)) puts("End of file reached successfully"); fclose(fp); }
二进制文件的例子:
#include <stdio.h> enum { SIZE = 5 }; int main(void) { double a[SIZE] = {1.,2.,3.,4.,5.}; FILE *fp = fopen("test.bin", "wb"); // 必须用二进制模式 fwrite(a, sizeof *a, SIZE, fp); // 写 double 的数组 fclose(fp); double b[SIZE]; fp = fopen("test.bin","rb"); size_t ret_code = fread(b, sizeof *b, SIZE, fp); // 读 double 的数组 if(ret_code == SIZE) { puts("Array read successfully, contents: "); for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]); putchar('\n'); } else { // error handling if (feof(fp)) printf("Error reading test.bin: unexpected end of file\n"); else if (ferror(fp)) { perror("Error reading test.bin"); } } fclose(fp); }
文件缓冲区
ANSIC 标准采用“缓冲文件系统”处理的数据文件的,所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块“文件缓冲区”。从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上。如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C编译系统决定的。
#include <stdio.h> #include <windows.h> int main() { FILE* pf = fopen("test.txt", "w"); fputs("abcdef", pf);//先将代码放在输出缓冲区 printf("睡眠10秒-已经写数据了,打开test.txt文件,发现文件没有内容\n"); Sleep(10000); printf("刷新缓冲区\n"); fflush(pf);//刷新缓冲区时,才将输出缓冲区的数据写到文件(磁盘) //注:fflush 在高版本的VS上不能使用了 printf("再睡眠10秒-此时,再次打开test.txt文件,文件有内容了\n"); Sleep(10000); fclose(pf); //注:fclose在关闭文件的时候,也会刷新缓冲区 pf = NULL; return 0; }
因为有缓冲区的存在,C语言在操作文件的时候,需要做刷新缓冲区或者在文件操作结束的时候关闭文
件。如果不做,可能导致读写文件的问题。