C语言文件操作
本章重点
什么是文件
文件名
文件类型
文件缓冲区
文件指针
文件的打开和关闭
文件的顺序读写
文件的随机读写
文件结束的判定
什么是文件
磁盘上的文件是文件
但是在程序设计中,我们一般谈的文件有两种:程序文件、数据文件
程序文件
包括源程序文件(后缀为.c),目标文件(windows环境后缀为.obj,Linux环境后缀为.o),可执行程序(windows环境后缀为.exe)
数据文件
文件的内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读取数据的文件,或者输出内容的文件
本章讨论的是数据文件
在以前各章所处理数据的输入输出都是以终端为对象的,即从终端的键盘输入数据,运行结果显示到显示器上。
其实有时候我们会把信息输出到磁盘上,当需要的时候再从磁盘上把数据读取到内存中使用,这里处理的就是磁盘上文件。
文件名
一个文件要有一个唯一的文件标识,以便用户识别和引用。
文件名包含3部分:文件路径+文件名主干+文件后缀
例如: c:\code\test.txt
文件路径+文件名主干+文件后缀
c:\code\ + test + .txt
为了方便起见,文件标识常被称为文件名。
文件类型
根据数据的组织形式,数据文件被称为文本文件或者二进制文件。
文本文件:全是ASCII字符存储
二进制文件:二进制存储,16进制显示
数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件。
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件。
一个数据在内存中是怎么存储的呢?
字符一律以ASCII形式存储,数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。
如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而二进制形式输出,则在磁盘上只占4个字节(VS2013测试)。
二进制文件写入10000,文件里是10 27 00 00,小端存储:十六进制的7210==十进制的10000
文本文件写入10000,文件里是10000,是字符'1' '0' '0' '0' '0'
测试代码:
#include <stdio.h>
int main()
{
int a = 10000;
//以二进制的写入形式打开test.txt文件,通过指针可以找到这个文件
FILE* pf = fopen("test.txt", "wb");
//将a写入,a占4个字节,写入1份,写到test.txt中
fwrite(&a, 4, 1, pf);//二进制的形式写到文件中
//结束文件
fclose(pf);
pf = NULL;
return 0;
}
文件缓冲区
ANSIC 标准采用“缓冲文件系统”处理的数据文件的,
所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块“文件缓冲区”。
从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上。
如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),
然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C编译系统决定的。
一秒结束后并没有输出,因为输出缓冲区没有满
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>
int main()
{
while (1)
{
Sleep(1000);//休息一秒
printf("hehe");
}
return 0;
}
文件指针
缓冲文件系统中,关键的概念是“文件类型指针”,简称“文件指针”。
每个被使用的文件都在内存中开辟了一个相应的文件信息区,
用来存放文件的相关信息(如文件的名字,文件状态及文件当前的位置等)。
这些信息是保存在一个结构体变量中的。该结构体类型是有系统声明的,取名FILE.
例如,VS2008编译环境提供的 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指向某个文件的文件信息区(是一个结构体变量)。通过该文
件信息区中的信息就能够访问该文件。也就是说,通过文件指针变量能够找到与它关联的文件。
比如:
文件的打开和关闭
文件在读写之前应该先打开文件,在使用结束之后应该关闭文件。
在编写程序的时候,在打开文件的同时,都会返回一个FILE*的指针变量指向该文件,也相当于建立了指针和文件的关系。
ANSIC 规定使用fopen函数来打开文件,fclose来关闭文件。
FILE * fopen ( const char * filename, const char * mode );
int fclose ( FILE * stream );
文件打开路径
绝对路径:为防止转移字符干扰,要加一个转义字符将其转义
FILE* fopen("C:\\Users\\93983\\source\\repos\\test_1_19.test.txt","r");
相对路径:
.. 表示上一级路径
. 表示当前路径
FILE* fopen("test.txt","r");//在源代码所在的目录
打开方式如下:
文件使用方式 | 含义 | 如果指定文件不存在 |
“r”(只读) | 为了输入数据,打开一个已经存在的文本文件 | 出错 |
“w”(只写) | 为了输出数据,打开一个文本文件 | 建立一个新的文件 |
“a”(追加) | 向文本文件尾添加数据 | 出错 |
“rb”(只读) | 为了输入数据,打开一个二进制文件 | 出错 |
“wb”(只写) | 为了输出数据,打开一个二进制文件 | 建立一个新的文件 |
“ab”(追加) | 向一个二进制文件尾添加数据 | 出错 |
“r+”(读写) | 为了读和写,打开一个文本文件 | 出错 |
“w+”(读写) | 为了读和写,建议一个新的文件 | 建立一个新的文件 |
“a+”(读写) | 打开一个文件,在文件尾进行读写 | 建立一个新的文件 |
“rb+”(读写) | 为了读和写打开一个二进制文件 | 出错 |
“wb+”(读写) | 为了读和写,新建一个新的二进制文件 | 建立一个新的文件 |
“ab+”(读写) | 打开一个二进制文件,在文件尾进行读和写 | 建立一个新的文件 |
实例代码:
/* fopen fclose example */
#include <stdio.h>
int main()
{
FILE* pFile;
pFile = fopen("myfile.txt", "w");
if (pFile != NULL)
{
fputs("fopen example", pFile);
fclose(pFile);
}
return 0;
}
文件的顺序读写
功能 | 函数名 | 适用于 |
字符输入函数 | fgetc | 所有输入流 |
字符输出函数 | fputc | 所有输出流 |
文本行输入函数 | fgets | 所有输入流 |
文本行输出函数 | fputs | 所有输出流 |
格式化输入函数 | fscanf | 所有输入流 |
格式化输出函数 | fprintf | 所有输出流 |
二进制输入 | fread | 文件 |
二进制输出 | fwrite | 文件 |
fgetc得到字符c函数(get是得到的意思)
函数原型
从文件指针指向的文件中获取一个字符,返回读取为int的字符或返回EOF以指示错误或文件结束
int fgetc( FILE *stream );
代码举例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE* pFile = fopen("test.txt", "r");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
int ch=fgetc(pFile);
printf("%c",ch);
ch = fgetc(pFile);
printf("%c", ch);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
test.txt内容hello
程序结果:he
*/
fputc输出字符c函数(put是给出的意思)
函数原型
向文件中输出一个字符,成功返回输出字符的ASCII码值,失败返回EOF
int fputc( int c, FILE *stream );
代码举例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE* pFile = fopen("test.txt", "w");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fputc('A',pFile);
fclose(pFile);
pFile = NULL;
return 0;
}
//跑过程序后test.txt中有A
fgets得到一行函数
从文件中得到一行字符串
函数原型
char *fgets( char *string, int n, FILE *stream );
- 返回值:NULL :EOF或成功结束 可以用 feof或 ferror判断错误位置
- string:存储文件中字符串的自己创建的字符串
- n:读取的最大数值
- stream:指向文件的指针
代码举例
test.txt内容
hello
world
test.c代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
char arr[1024] = { 0 };
FILE* pFile = fopen("test.txt", "r");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fgets(arr,1024,pFile);
printf("%s",arr);
fclose(pFile);
pFile = NULL;
return 0;
}
/*结果
hello
*/
fputs字符串写入函数
函数原型
int fputs( const char *string, FILE *stream );
- 返回值:如果成功,返回一个非负值。出错时,返回EOF
- string:要输出字符串
- stream:指向文件结构的指针
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE* pFile = fopen("test.txt", "w");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fputs("hello world",pFile);
fclose(pFile);
pFile = NULL;
return 0;
}
/*结果
test.txt内容
hello world
*/
fscanf从文件中读取格式化数据
格式:就是类型,例如int float char double型
函数原型
int fscanf( FILE *stream, const char *format [, argument ]... );
类比scanf:多了文件来源
int scanf( const char *format [,argument]... );
fscanf从文件读取格式化数据
scanf从标准输入设备-键盘(stdin)读取数据
PS:标准输出设备-显示屏(stdout)
返回值:返回成功转换和分配的字段数;返回值不包括已读取但未分配的字段。返回值0表示未分配任何字段。发生错误,或者在第一次转换之前到达文件流的结尾,则返回值为EOF
代码实践:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
struct Student
{
char name[20];
int age;
float score;
};
int main()
{
struct Student s = { 0 };
FILE* pFile = fopen("test.txt", "r");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fscanf(pFile,"%s %d %f",&s.name,&s.age,&s.score);
printf("%s %d %f", s.name, s.age, s.score);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
test.txt内容
zhangsan 18 98.5
结果
zhangsan 18 98.500000
*/
fprintf向文件输出格式化数据
函数原型
int fprintf( FILE *stream, const char *format [, argument ]...);
对比printf,只多了文件输出的对象
int printf( const char *format [, argument]... );
返回值:fprintf返回写入的字节数。当发生输出错误时,返回一个负值。
代码实践:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
struct Student
{
char name[20];
int age;
float score;
};
int main()
{
struct Student s = { "zhangsan" ,18, 98.5f };
FILE* pFile = fopen("test.txt", "w");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fprintf(pFile,"%s %d %f",s.name,s.age,s.score);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
结果txt中内容为
zhangsan 18 98.500000
*/
fread二进制输入
函数原型
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
返回值:fread返回实际读取的完整项目数,如果发生错误或在达到count之前遇到文件结尾,则该值可能小于count。使用feof或feror函数来区分读取错误和文件结束条件。如果size或count为0,则fread返回0且缓冲区内容不变。
buffer缓冲器:数据的存储位置
size:项目大小(字节)
count:要读取的最大项目数
stream:指向文件结构的指针
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
char arr[1024] = { 0 };
FILE* pFile = fopen("test.txt", "rb");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fread(arr, sizeof(char), 9, pFile);
printf("%s\n",arr);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
txt中内容为
abcdef123
结果为
abcdef123
*/
写一个数据进文件
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
- buffer缓冲器:指向要写入的数据的指针
- size:项目大小(字节)
- count:要写入的最大项目数
- stream:指向文件结构的指针
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
char arr[1024] = { 0 };
char str[] = "abcdef123";
FILE* pFile = fopen("test.txt", "wb");
if (pFile == NULL)
{
printf("%s\n", strerror(errno));
return 0;
}
fwrite(str, sizeof(char), sizeof(str), pFile);
//fread(arr, sizeof(char), 4, pFile);
//printf("%s\n",arr);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
结果txt中内容为
abcdef123
*/
区别scanf/fscanf/sscanf
scanf是从标准输入设备,也就是键盘上获取格式化内容
fscanf是从数据文件中获取格式化内容
sscanf是从字符串中获取格式化内容
#define _CRT_SECURE_NO_WARNINGS
//函数原型
//int sscanf( const char *buffer, const char *format [, argument ] ... );
#include <stdio.h>
int main()
{
char str[10] = { 0 };
int a = 0;
float b = 0.0f;
char arr[] = "abc 123 3.14";
sscanf(arr,"%s %d %f",&str,&a,&b);
printf("%s\n",str);
printf("%d\n",a);
printf("%f\n",b);
return 0;
}
/*
结果:
abc
123
3.140000
*/
区别printf/fprintf/sprintf
printf是向标准输出设备,也就是显示屏,输出格式化内容
fprintf是向文件中输出格式化内容
sprintf是向字符串输出格式化内容
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//函数原型
//int sprintf(char* buffer, const char* format[, argument] ...);
int main()
{
char str[10] ="hello";
int a = 2021;
float b = 3.14f;
char arr[1024] = {0};
sprintf(arr,"%s %d %f",str,a,b);
printf("%s\n",arr);
return 0;
}
/*
结果:
hello 2021 3.140000
*/
文件的随机读写
fseek 根据文件指针的位置和偏移量来定位文件指针
函数原型:
int fseek ( FILE * stream, long int offset, int origin );
- 返回值:如果成功,fseek返回0。否则,它将返回一个非零值。在无法查找的设备上,返回值未定义。
- stream:指向文件结构的指针
- offset:偏移量
- origin:指针初始位置
- SEEK_SET 第1个字符,指向接下来要操作的首字节位置
- SEEK_CUR 当前字符位置
- SEEK_END 最后一个字符的后一个位置
例子:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
FILE* pFile;
pFile = fopen("test.txt", "wb");
fputs("This is an apple.", pFile);
fseek(pFile, 9, SEEK_SET);
fputs("sam", pFile);
fclose(pFile);
return 0;
}
/*结果
test.txt内容This is asampple.
This is an apple.
T偏移量为0
h偏移量为1
i偏移量为2
......
n偏移量为9 <--------文件指针pFile指向此处
偏移量为10
......
*/
ftell
返回文件指针相对于起始位置的偏移量
函数原型
long int ftell ( FILE * stream );
例子:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
FILE* pFile;
long size;
pFile = fopen("test.txt", "rb");
if (pFile == NULL) perror("Error opening file");
else
{
fseek(pFile, 0, SEEK_END); //将指针移动到末尾
size = ftell(pFile);
fclose(pFile);
printf("Size of test.txt: %ld bytes.\n", size);
}
return 0;
}
PS:错误报告函数
方法一:
perror("Error opening file");
结果:Error opening file: XXXXXX
方法二:
#include <string.h>
#include <errno.h>
printf("%s\n", strerror(errno));
结果:XXXXXX
rewind
让文件指针的位置回到文件的起始位置
void rewind ( FILE* stream );
例子:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
FILE* pFile=fopen("test.txt", "r");
if (pFile == NULL) perror("Error opening file");
fseek(pFile,-1,SEEK_END);//指针移动到o
rewind(pFile);//指针移动到h
int ch=fgetc(pFile);
printf("%c",ch);
fclose(pFile);
pFile = NULL;
return 0;
}
/*
txt:hello
结果:h
*/
文件结束判定
被错误使用的 feof
牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束。
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束。
1. 文本文件读取是否结束,判断返回值是否为文件尾结束EOF (fgetc),或者读取失败结束NULL(fgets)
例如:
fgetc判断是否为EOF.
fgets判断返回值是否为NULL.
2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
例如:
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;//stdlib.h中有#define EXIT_FAILURE 1
}
//fgetc 当读取失败的时候或者遇到文件结束的时候,都会返回EOF
while ((c = fgetc(fp)) != EOF) // 标准C I/O读取文件循环
{
putchar(c);
}
//判断是什么原因结束的
if (ferror(fp))//如果fp中没有发生错误,ferror将返回0。否则,它将返回一个非零值
puts("I/O error when reading");
else if (feof(fp))
//feof函数在第一次读取操作后返回一个非零值,
//该操作试图读取文件的末尾。
//如果当前位置不是文件结尾,则返回0
puts("End of file reached successfully");
fclose(fp);
}
二进制文件的例子:
#include <stdio.h>
enum { SIZE = 5 };
int main(void)
{
double a[SIZE] = { 1.0,2.0,3.0,4.0,5.0 };
double b = 0.0;
size_t ret_code = 0;
FILE* fp = fopen("test.bin", "wb"); // 必须用二进制模式
fwrite(a, sizeof(*a), SIZE, fp); // 写 double 的数组
fclose(fp);
fp = fopen("test.bin", "rb");
// 读 double 的数组
while ((ret_code = fread(&b, sizeof(double), 1, fp)) >= 1)
{
printf("%lf\n", b);
}
if (feof(fp))
printf("Error reading test.bin: unexpected end of file\n");
else if (ferror(fp)) {
perror("Error reading test.bin");
}
fclose(fp);
fp = NULL;
}