目录
一、什么是文件
1.1 程序文件
1.2 数据文件
1.3 文件名
二、文件的打开和关闭
2.1 文件指针
2.2 文件的打开和关闭
2.3 文件的顺序读写编辑
三、文件的随机读写
3.1 fseek、ftell、rewind
四、文本文件和二进制文件
五、文件读取结束的判定
5.1 被错误使用的feof
六、文件缓冲区
一、什么是文件
磁盘上的文件是文件。
但是在程序设计中,我们一般谈的文件有两种:程序文件、数据文件(从文件功能的角度来分类的)。
1.1 程序文件
包括源程序文件(后缀为.c),目标文件(windows环境后缀为.obj),可执行程序(windows环境 后缀为.exe)。
1.2 数据文件
文件的内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读取数据的文件, 或者输出内容的文件。
1.3 文件名
一个文件要有一个唯一的文件标识,以便用户识别和引用。
文件名包含3部分:文件路径+文件名主干+文件后缀
例如: c:\code\test.txt
为了方便起见,文件标识常被称为文件名。
二、文件的打开和关闭
2.1 文件指针
缓冲文件系统中,关键的概念是“文件类型指针”,简称“文件指针”。
每个被使用的文件都在内存中开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名字,文件状态及文件当前的位置等)。这些信息是保存在一个结构体变量中的。该结构体类型是由系统声明的,取名FILE.
例如,VS2013编译环境提供的 stdio.h 头文件中有以下的文件类型申明:
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
不同的C编译器的FILE类型包含的内容不完全相同,但是大同小异。
每当打开一个文件的时候,系统会根据文件的情况自动创建一个FILE结构的变量,并填充其中的信息, 使用者不必关心细节。 一般都是通过一个FILE的指针来维护这个FILE结构的变量,这样使用起来更加方便。 下面我们可以创建一个FILE*的指针变量:
FILE* pf;//文件指针变量
定义pf是一个指向FILE类型数据的指针变量。可以使pf指向某个文件的文件信息区(是一个结构体变量)。通过该文件信息区中的信息就能够访问该文件。也就是说,通过文件指针变量能够找到与它关联的文件。
比如:
2.2 文件的打开和关闭
文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。
在编写程序的时候,在打开文件的同时,都会返回一个FILE*的指针变量指向该文件,也相当于建立了指 针和文件的关系。
ANSIC 规定使用fopen函数来打开文件,fclose来关闭文件。
//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream );
实例代码:
/* fopen fclose example */
#include <stdio.h>
int main ()
{
FILE * pFile;
//打开文件
pFile = fopen ("myfile.txt","w");//此时的myfile为相对路径
//pFile = fopen ("c:\\code\\myfile.txt","w");此时的myfile为绝对路径
//文件操作
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
//关闭文件
fclose (pFile);
}
return 0;
}
2.3 文件的顺序读写
fputc
int fputc ( int character , FILE * stream);
用法:
int main()
{
//打开文件
FILE* pf = fopen("test.txt", "w");
if (NULL == pf)
{
perror("fopen");
return 1;
}
//写文件
int i = 0;
for (int i = 0; i < 26; i++)
{
fputc('a' + i, pf);
}
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
fgetc
int fgetc ( file * stream );
成功后,将返回字符读取(提升为 int 值)。
返回类型为 int 以容纳指示失败的特殊值 EOF:
如果位置指示器位于文件末尾,则该函数返回 EOF 并设置流的 eof 指示器 (feof)。
如果发生其他读取错误,该函数也会返回 EOF,但会设置其错误指示器 (ferror)。
用法:
int main()
{
FILE* pf = fopen("test.txt", "r");
if (NULL == pf)
{
perror("fopen");
return 1;
}
int i = 0;
int ch = 0;
//for (int i = 0; i < 26; i++)
//{
// ch=fgetc(pf);
// printf("%c ", ch);
//}
while ((ch=fgetc(pf)) != EOF)
{
printf("%c ", ch);
}
fclose(pf);
pf = NULL;
return 0;
}
fpupts
int fputs ( const char * str , FILE * stream);
用法:
int main()
{
FILE* pf = fopen("test.txt", "w");
if (NULL == pf)
{
perror("fopen");
return 1;
}
fputs("hello\n", pf);
fputs("world\n", pf);//不会自动换行,根据自己需求换行
fclose(pf);
pf = NULL;
return 0;
}
fgets:
char * fgets ( char * str , int num ,FILE * stream );
从流中读取字符并将其作为 C 字符串存储到 str 中,直到读取 (num-1) 个字符或到达换行符或文件结尾,以先发生者为准。
换行符使 fgets 停止读取,但它被函数视为有效字符,并包含在复制到 str 的字符串中。
终止空字符会自动追加到复制到 str 的字符之后。
请注意,fgets 与 get 完全不同:fgets 不仅接受流参数,还允许指定 str 的最大大小,并在字符串中包含任何结束换行符。
用法:
int main()
{
FILE* pf = fopen("test.txt", "r");
if (NULL == pf)
{
perror("fopen");
return 1;
}
char arr[20]="#########";
fgets(arr, 15, pf);
printf("%s",arr);
fgets(arr, 15, pf);
printf("%s",arr);
fclose(pf);
pf = NULL;
return 0;
}
fprintf:
int fprintf ( FILE * stream , const char * format , ...);
用法:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",23,3.2f };
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fprintf(pf,"%s %d %.2f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
fscanf:
int fscanf ( FILE * stream , const char * format ,...);
用法:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",23,3.2f };
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fscanf(pf, "%s %d %.2f", s.name, &s.age, &s.score);
printf("%s %d %.2f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
fwrite
size_t fwrite ( const void * ptr , size_t size , size_t count , FILE * stream);
用法:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",23,3.2f };
FILE* pf = fopen("text.txt", "wb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fwrite(&s, sizeof(struct S),1,pf);
fclose(pf);
pf = NULL;
return 0;
}
fread:
size_t fread ( void * ptr , size_ t size , size_t count , FILE * stream);
用法:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",23,3.2f };
FILE* pf = fopen("text.txt", "rb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %.2f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
sprintf:
int sprintf ( char * str , const char * format, ... );
sscanf:
int sscanf (const char * s , const char * format , . . . );
用法:
struct S
{
char name[20];
int age;
float score;
};
int main()
{
struct S s = { "zhangsan",23,3.2f };
char arr[100] = { 0 };
struct S s1 = { 0 };
sprintf(arr,"%s %d %f",s.name,s.age,s.score);
printf("%s\n", arr);
sscanf(&s, "%s %d %f", s.name, s.age, s.score);
printf("%s %d %.2f\n", s.name, s.age, s.score);
return 0;
}
综上:
scanf : 按照一定的格式从键盘输入数据
printf : 按照一定的格式把数据打印到屏幕上
//适用于标准输入/输出流的格式化的输入/输出语句
fscanf : 按照一定的格式从输入流(文件/stdin)输入数据
fprintf: 按照一定的格式向输出流(文件/stdout)输出数据
// 适用于所有的输入/输出流的格式化输入/输出语句
sscanf : 从字符串中按照一定的格式读取出格式化的数据
sprintf : 把格式化的数据按照一定的格式转换成字符串
三、文件的随机读写
3.1 fseek、ftell、rewind
int fseek ( FILE * stream, long int offset, int origin );
根据文件的位置和偏移量来定位文件指针。
用法:
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen()");
return 1;
}
//从前往后读
//fseek(pf, 3, SEEK_SET);
//int ch = fgetc(pf);
//printf("%c\n", ch);
// 从后往前读
//fseek(pf, -3, SEEK_END);
//int ch = fgetc(pf);
//printf("%c\n", ch);
//从当前位置往后偏移
int ch = getc(pf);
fseek(pf, 1, SEEK_CUR);
ch = getc(pf);
printf("%c\n", ch);
int pos = ftell(pf);//返回值为当前位置相对于起始位置偏移量
printf("%d\n", pos);
rewind(pf);//返回起始位置
ch = getc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
四、文本文件和二进制文件
根据数据的组织形式,数据文件被称为文本文件或者二进制文件。
数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件。
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件。
字符一律以ASCII形式存储,数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。 如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而 二进制形式输出,则在磁盘上只占4个字节。
五、文件读取结束的判定
5.1 被错误使用的feof
牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束。 而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束。
1. 文本文件读取是否结束,判断返回值是否为 EOF ( fgetc ),或者 NULL ( fgets )
例如:
fgetc 判断是否为 EOF .
fgets 判断返回值是否为 NULL .
正确的使用:
文本文件的例子:
#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);
}
2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
例如:
fread判断返回值是否小于实际要读的个数。
二进制文件的例子:
#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编译系统决定的。