深度解析C语言文件操作

1.为什么要使用文件

我们前面学习结构体时,写了通讯录的程序,当通讯录运行起来的时候,可以在通讯录中添加、删除数据,此时数据是存放在内存中的,当程序退出的时候,通讯录中的数据自然就不存在了,等下次运行通讯录时,数据又得重新导入,如果这样使用通讯录就很难受。
既然是通讯录就应该记录下来,只有我们自己选择删除数据得时候,数据才不复存在。这就涉及到了数据得持久化得问题,我们一般数据持久化得方法有,把数据存放在磁盘文件、存放到数据库等方式。
使用文件我们就可以将数据存放在电脑的硬盘上,做到数据的持久化。

2.什么是文件

磁盘上的文件就是文件。
但是在程序设计中,从文件的功能角度来分类,我们一般谈的文件有两种:程序文件、数据文件。

2.1 程序文件

包括源程序文件(后缀为.c),目标文件(windows环境后缀为.obj),可执行程序(windows环境后缀为.exe)。

2.2 数据文件

文件的内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读取数据的文件,或者输出内容的文件.

本文讨论的数据文件.
在以前文章所处理的数据的输入输出都是以终端为对象的,即从终端的键盘输入数据,运行结果显示到显示屏上.
其实有时候我们会把信息输出到磁盘上,当需要的时候再从磁盘上把数据读取到内存中使用,这里处理的就是磁盘上文件.

2.3 文件名

一个文件要有唯一的文件标识,以便于用户识别和引用.
文件名包括3个部分:文件路径+文件名主干+文件后缀
例如:c:\code\test.txt
为了方便,文件的标识通常被称为文件名.

3.文件的打开和关闭

缓冲文件系统中,关键的概念是"文件类型指针",简称"文件指针".
每个被使用的文件都在内存中开辟了一个相对应的文件信息区,用来存放文件的相关信息(如文件的名字,文件的状态以及文件当前所处的位置).这些信息是保存在一个结构体变量中的.这个结构体类型是系统声明的,取名叫FILE.
例如,在vs编译环境下提供的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指向某个文件的文件信息区(是一个结构体变量).通过该文件信息区中的信息就能够访问该文件.也就是说,通过文件指针变量能够找到于它关联的文件.
文件信息区

3.2 文件的打开和关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件.
在编写程序的时候,在打开文件的同时,都会返回一个FILE*的指针变量指向该文件,也相当于建立了指针于文件的关系.
ANSIC规定使用fopen函数来打开文件,fclose来关闭文件.

//打开文件
FILE* fopen(const char* filename,const char* mode);
//关闭文件
int fclose(FILE* stream);

打开方式:

文件使用方式含义如果指定文件不存在
“r”(只读)为了输入数据,打开一个已经存在的文本文件出错
“w”(只写)为了输出数据,打开一个文本文件建立一个新的文件
“a”(追加)向文本文件尾添加数据建立一个新的文件
“rb”(只读)为了输入数据,打开一个二进制文件出错
“wb”(只写)为了输出数据,打开一个二进制文件建立一个新的文件
“ab”(追加)向一个二进制文件尾添加数据出错
“r+”(读写)为了读和写,打开一个文本文件出错
“w+”(读写)为了读和写,建立一个新的文件建立一个新的文件
“a+”(读写)打开一个文件,在文件尾进行续写建立一个新的文件
“rb+”(读写)为了读和写打开一个二进制文件出错
“wb+”(读写)为了读和写,新建一个二进制文件建立一个新的文件
“ab+”(读写)打开一个二进制文件,在文件尾进行读和写建立一个新的文件
code
#include <stdio.h>
int main()
{
	FILE* pf;
	//打开文件
	pf = fopen("test.txt","w");
	//文件操作
	if(pf==NULL)//打开出错
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world",pf);
	//关闭文件
	fclose(pf);
	return 0;
}

//程序运行的结果:
/*
和源文件在一个路径底下会出现一个test.txt的文件,文件的内容是:hello world
*/

test.txt

4.文件的顺序读写

功能函数名使用于
字符输入函数fgetc所有输入流
字符输出函数fputc所有输出流
文本行输入函数fgets所有输入流
文本行输出函数fputs所有输出流
格式化输入函数fscanf所有输入流
格式化输出函数fprintf所有输出流
二进制输入fread文件
二进制输出fwrite文件

4.1 fgetc

int fgetc(FILE*stream);

Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character.
If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof).
If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror).
fgetc and getc are equivalent, except that getc may be implemented as a macro in some libraries.
简单解释,fgetc可以按顺序从前到后从指定的文件中提取字符,以ASCII表的形式返回。

//代码1
#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if(pf==NULL)
	{
		//错误处理
	}
	fputc('w', pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

//先执行代码一再执行代码2,先把数据存入test.txt中

//代码2
#include <stdio.h>
int main()
{
	FILE* pfile = fopen("test.txt", "r");
	if (pfile == NULL)
	{
		//错误处理
	}
	printf("%c\n",fgetc(pfile));
	fclose(pfile);
	pfile = NULL;
	return 0;
}
//打印结果:
//w

4.2 fputc

int fputc(int charcter,FILE* stream);

Writes a character to the stream and advances the position indicator.
写一个字符到指定的文件中。

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if(pf==NULL)
	{
		//错误处理
	}
	fputc('w', pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

4.3 fgets

char* fgets(char* str,int num,FILE* stream);

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
fgets函数的功能就是:读取指定文件内的num-1个字符到str中,读完num-1个字符停止,读到文件末尾也会停止。

//test.txt中存储的是:hello world!!!!!
#include <stdio.h>

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	char str[20];
	fgets(str, 10, pf);
	printf("%s\n", str);
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果
/*
hello wor
*/

4.4fputs

int fputs(const char* str,FILE*stream);

Writes the C string pointed by str to the stream.
将str中的字符串输入到指定文件。

#include <stdio.h>

int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	char str[20] = "hello Yui!!!!";
	fputs(str, pf);
	fclose(pf);
	pf = NULL;
	return 0;
}
//文件test.txt的内容:
/*
hello Yui!!!!
*/

4.5 fscanf

int fscanf(FILE* stream,const char* format,...);

Reads data from the stream and stores them according to the parameter format into the locations pointed by the additional arguments.
函数功能:从指定流中读取内容,为函数中给定的变量赋值

//文件test.txt的内容为:y 10 3.140000
#include <stdio.h>
struct S
{
	char c;
	int i;
	float f;
};

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s;
	fscanf(pf,"%c %d %f",&s.c,&s.i,&s.f);
	printf("%c %d %f", s.c, s.i, s.f);
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果:
/*
y 10 3.140000
*/

4.6fprintf

int fprintf(FILE* stream,const char* format,...);

Writes the C string pointed by format to the stream. If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
函数功能:把format的内容写进指定流。

#include <stdio.h>

struct S
{
	char c;
	int i;
	float f;
};

int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s = { 'y',10,3.14f };
	//fscanf(pf,"%c %d %f",&s.c,&s.i,&s.f);
	fprintf(pf, "%c %d %f", s.c, s.i, s.f);
	fclose(pf);
	pf = NULL;
	return 0;
}
//文件test.txt的内容:
/*
y 10 3.140000
*/

4.7 fread

size_t fread(void* ptr,size_t size,size_t count,FILE* stream);

Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr.
函数功能:将指定文件中,每个元素为size字节的数量为count个的内容解读二进制后传递给ptr
fread

//文件test.txt的内容为:
/*
챹쳌
 䁈
*/
#include <stdio.h>
struct S
{
	char c;
	int i;
	float f;
};

int main()
{
	FILE* pf = fopen("test.txt", "rb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s;
	fscanf(pf,"%c %d %f",&s.c,&s.i,&s.f);
	printf("%c %d %f", s.c, s.i, s.f);
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果:
/*
y 10 3.140000
*/

4.8 fwrite

size_t fwrite(const void* ptr,size_t size,size_t count,FILE* stream);

Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream.
函数功能:将ptr指向的每个元素大小为size字节的数量为count个的内容以二进制的形式输入进指定文件。
fwrite

#include <stdio.h>

struct S
{
	char c;
	int i;
	float f;
};

int main()
{
	FILE* pf = fopen("test.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	struct S s = { 'y',10,3.14f };
	fwrite(&s, sizeof(s), 1, pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

//文件test.txt内容:
/*
챹쳌
 䁈
*/

对比一组函数

scanf/ fscanf/ sscanf
printf/fprintf/sprintf

scanf:对标准输入流读取格式的数据。
printf:向标准输出流写格式化的数据。

fscanf:适用于所有流的格式输入函数输入函数。
fprintf:适用于所有输出流的格式化输出函数。

sscanf:从字符串中读取格式化的数据。
sprintf:将格式化的数据,转换成字符串。

5.文件的随机读写

5.1 fseek

根据文件指针的位置和偏移量来定位文件指针

注意以文本文件打开的的流,必须设置为SEEK_SET

fseek

int fseek(FILE* stream,long int offset,int origin);

#include <stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world!", pf);
	fseek(pf, 9, SEEK_SET);
	fputs(" yui", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}
//test.txt文件内容:
/*
hello wor yui
*/

5.2 fteel

返回文件指针相对于起始位置的偏移量

long int ftell(FILE* stream);
#include <stdio.h>

int main()
{
	FILE* pf = fopen("test.txt","rb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fseek(pf,0,SEEK_END);
	long size = ftell(pf);
	printf("%ld\n",size);
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果:
//13

解释:因为文件中的内容为:hello wor yui
SEEK_END是左右是让文件指针指向文件的末尾,该文件更好13个字符,指向末尾就是指向i。

5.3 rewind

让文件指针回到文件的起始起始位置

void rewind(FILE* stream);

#include <stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w+");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	int n = 0;
	char buffer[27];
	for (n = 'A'; n <= 'Z'; ++n)
	{
		fputc(n, pf);
	}
	rewind(pf);
	fread(buffer, 1, 26, pf);
	fclose(pf);
	buffer[26] = '\0';
	puts(buffer);
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果
//ABCDEFGHIJKLMNOPQRSTUVWXYZ

rewind人文件指针回到初始位置,如果不加rewind则不会打印出任何字符。

6.文本文件和二进制文件

根据数据的组织形式,数据文件被称为文本文件或者二进制文件
数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件
一个数据在内存中是怎么存储的呢?
字符一律以ASCII形式存储数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储。
比如,整数10000如果以ASCII码形式输出磁盘,则磁盘占用5个字节(一个字符占一个字节),而二进制形式输出,则在磁盘上只占4个字节(10 27 00 00)16进制显示。
内存中以二进制存储

#include <stdio.h>
int main()
{
	int a = 10000;
	FILE* pf = fopen("test.txt","wb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fwrite(&a,4,1,pf);
	fclose(pf);
	pf = NULL;
	return 0;
}
//文件内容
/*
'  
*/

以二进制编译器打开

确定后就会显示
显示

前面的00000000不用管

7. 文件读取结束的判定

7.1 被误用的feof

牢记:在文件读取过程中,不能用feof函数的返回值直接判断文件的是否结束。
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件末尾结束
1.文本文件读取是否结束,判断返回值是否是EOF(fgetc),或者NULLfgets
例如:

  • fgetc判断是否为EOF
  • fgets判断返回值是否为NULL
    2.二进制文件的读取结束判断,判断返回值是否小于实际要读的个数。
  • fread判断返回值是否小于实际要的的个数。
    正确的用法。
    文本文件
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int c = 0;
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//fgetc当读取失败或者遇到文件末尾会返回EOF
	while ((c = fgetc(pf)) != EOF)
	{
		putchar(c);
	}
	//判断是什么原因结束的
	if (ferror(pf))
		puts("I/O error when reading\n");
	else if(feof(pf))
		puts("End of file reached successfully\n");
	fclose(pf);
	pf = NULL;
	return 0;
}
//打印结果:
//End of file reached successfully

二进制文件

#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);
	fp = NULL;
	return 0;
}
//打印结果:
/*
Array read successfully, contents:
1.000000 2.000000 3.000000 4.000000 5.000000
*/

8.文件缓冲区

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语言再操作文件的时候,需要做刷新缓冲区或者在文件操作结束的时候关闭文件。
如果不做,可能导致读写文件的问题。

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yui_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值