【进阶】6. 文件操作

文章说明:该文章的知识点源于B站上比特鹏哥的C语言课程,结合鹏哥上课的讲义、课堂代码以及自己的理解整理形成。

1. 为什么使用文件

我们前面学习结构体时,写了通讯录的程序,当通讯录运行起来的时候,可以给通讯录中增加、删除数据,此时数据是存放在内存中,当程序退出的时候,通讯录中的数据自然就不存在了,等下次运行通讯录程序的时候,数据又得重新录入,如果使用这样的通讯录就很难受。

我们在想既然是通讯录就应该把信息记录下来,只有我们自己选择删除数据的时候,数据才不复存在。

这就涉及到了数据持久化的问题,我们一般数据持久化的方法有,把数据存放在磁盘文件、存放到数据库等方式

使用文件我们可以将数据直接存放在电脑的硬盘上,做到了数据的持久化

2. 什么是文件

文件通常指的是磁盘上的文件。

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

2.1 程序文件

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

2.2 数据文件

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

本章讨论的是数据文件。

在以前各章所处理数据的输入输出都是以终端为对象的,即从终端的键盘输入数据,运行结果显示到显示器上。

有时候我们会把信息输出到磁盘上,当需要的时候再从磁盘上把数据读取到内存中使用,这里处理的就是磁盘上文件。

2.3 文件名

一个文件要有一个唯一的文件标识,以便用户识别和引用。

文件名包含3部分:文件路径+文件名主干+文件后缀

例如:c:\code\test.txt

文件路径:c:\code 文件名主干:test 文件后缀:.txt

为了方便起见,文件标识常被称为文件名。

3. 文件的打开和关闭

3.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 指向某个文件的文件信息区(是一个结构体变量)。通过该文件信息区中的信息就能够访问该文件。也就是说,文件信息区和该文件想关联通过文件指针变量能够找到与它关联的文件。

3.2 文件的打开和关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件

在编写程序的时候,在打开文件的同时,都会返回一个FILE*的指针变量指向该文件,也相当于建立了指针和文件的关系。

ANSIC 规定使用 fopen 函数来打开文件,fclose 来关闭文件。

//打开文件
FILE * fopen ( const char * filename, const char * mode );
//const char * filename : 文件名字
//const char * mode : 打开方式

打开方式如下:

文件使用方式含义如果指定文件不存在
“r”(只读)为了输入数据,打开一个已经存在的文本文件出错
“w”(只写)为了输出数据,打开一个文本文件建立一个新的文件
“a”(追加)向文本文件尾添加数据建立一个新的文件
“rb”(只读)为了输入数据,打开一个二进制文件出错
“wb”(只写)为了输出数据,打开一个二进制文件建立一个新的文件
“ab”(追加)向一个二进制文件尾添加数据出错
“r+”(读写)为了读和写,打开一个文本文件出错
“w+”(读写)为了读和写,建议一个新的文件建立一个新的文件
“a+”(读写)打开一个文件,在文件尾进行读写建立一个新的文件
“rb+”(读写)为了读和写打开一个二进制文件出错
“wb+”(读写)为了读和写,新建一个新的二进制文件建立一个新的文件
“ab+”(读写)打开一个二进制文件,在文件尾进行读和写建立一个新的文件
//关闭文件
int fclose ( FILE * stream );

If the stream is successfully closed, a zero value is returned.

On failure, EOF is returned.

int main()
{
    //绝对路径的双\是因为转义字符
	FILE* pf = fopen("D:\\2021_code\\class101\\test_7_20\\test.dat", "r"); //绝对路径
    FILE* pf = fopen("test.dat", "r"); //相对路径
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4. 文件的顺序读写

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

流是一个高度抽象的概念。

程序如果要向屏幕、硬盘、U盘、光盘、网络、软盘等读取或者写入数据,由于这些硬件的读写方式不同,因此,这对于程序员来说要求太高了,中间抽象出“流”这个层。程序员只需要把数据输入到“流”中或者从“流”中读取数据,至于如何将数据输入到硬件上或者从硬件上读取数据,这是“流”关心的事情,程序员无需关心。

一个C语言程序,只要运行起来,就默认打开了3个流,它们的类型都是 FILE *

  1. stdin - 标准输入流 - 键盘
  2. stdout - 标准输出流 - 屏幕
  3. stderr - 标准错误流 - 屏幕

4.1 fputc

//Writes a character to a stream (fputc, fputwc) or to stdout 

int fputc( int c, FILE *stream );

//c : Character to be written
//stream : Pointer to FILE structure

//Return Value : Each of these functions returns the character written. A return value of EOF indicates an error. 
//向文件中写入
int main()
{
	FILE* pf = fopen("test.dat", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	fputc('b', pf);
	fputc('i', pf);
	fputc('t', pf);

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}
//向屏幕写入
int main()
{
	fputc('b', stdout);
	fputc('i', stdout);
	fputc('t', stdout);

	return 0;
}

4.2 fgetc

//Read a character from a stream (fgetc, fgetwc) or stdin 

int fgetc( FILE *stream );

//stream : Pointer to FILE structure

//Return Value : fgetc return the character read as an int or return EOF to indicate an error or end of file.

读取文件结束或者读取错误会返回 EOF (-1)

//使用fgetc从文件流中读取数据
int main()
{
	FILE* pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读文件
	int ret = fgetc(pf);
	printf("%c\n", ret);
    ret = fgetc(pf);
	printf("%c\n", ret);
	ret = fgetc(pf);
	printf("%c\n", ret);
	ret = fgetc(pf);
	printf("%c\n", ret);
	ret = fgetc(pf);
	printf("%c\n", ret);
	ret = fgetc(pf);
	printf("%c\n", ret);
	ret = fgetc(pf);
	printf("%c\n", ret);

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

//fgetc从标准输入流读取
int main()
{
	int ret = fgetc(stdin);
	printf("%c\n", ret);
	ret = fgetc(stdin);
	printf("%c\n", ret);
	ret = fgetc(stdin);
	printf("%c\n", ret);

	return 0;
}

4.3 fputs

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

//string : Output string
//stream : Pointer to FILE structure

//Return Value : Each of these functions returns a nonnegative value if it is successful. On an error, fputs returns EOF.
int main()
{
	FILE* pf = fopen("test.dat", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件-按照行来写
	fputs("abcdef\n", pf); //要让文件换行必须加\n
	fputs("qwertyuiop\n", pf);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.4 fgets

char *fgets( char *string, int n, FILE *stream );

//string : Storage location for data
//n : Maximum number of characters to read -> 实际上最大只能读取n-1字符,最后一个字符是\0
//stream : Pointer to FILE structure

//Return Value : Each of these functions returns string. NULL is returned to indicate an error or an end-of-file condition.
int main()
{
	char arr[10] = { 0 };
	FILE* pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//读文件
	fgets(arr, 4, pf); //最后1个字符是\0,所以最多只能读3个
	printf("%s\n", arr);
	
	fgets(arr, 4, pf);
	printf("%s\n", arr);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.5 fprintf

printffprintf 对比

int printf( const char *format [, argument]... );
int fprintf( FILE *stream, const char *format [, argument ]...); //只多了文件指针

如果将 stream 的参数设置为 stdout ,那么 fprintf 的效果等价于 printf

int main()
{
	struct S s = { "abcdef", 10, 5.5f };
	//对格式化的数据进行写文件
	FILE*pf = fopen("test.dat", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	fprintf(pf, "%s %d %f", s.arr, s.num, s.sc);

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.6 fscanf

scanffscanf 对比:

int scanf( const char *format [,argument]... );
int fscanf( FILE *stream, const char *format [, argument ]... ); //只多了文件指针

如果将 stream 的参数设置为 stdin ,那么 fscanf 的效果等价于 scanf

struct S
{
	char arr[10];
	int num;
	float sc;
};

int main()
{
	struct S s = {0};
	//对格式化的数据进行写文件
	FILE* pf = fopen("test.dat", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	//读文件
	fscanf(pf, "%s %d %f", s.arr, &(s.num), &(s.sc)); //取地址

	//打印
	fprintf(stdout, "%s %d %f\n", s.arr, s.num, s.sc);
	//printf("%s %d %f\n", s.arr, s.num, s.sc); 效果同上
    
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

4.7 fwrite

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

//buffer : Pointer to data to be written
//size : Item size in bytes
//count : Maximum number of items to be written
//stream : Pointer to FILE structure

//Return Value : fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.
struct S
{
	char arr[10];
	int num;
	float sc;
};

int main()
{
	struct S s = { "abcde", 10, 5.5f };
	//二进制的形式写
	FILE*pf = fopen("test.dat", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	fwrite(&s, sizeof(struct S), 1, pf);

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

4.8 fread

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

//buffer : Storage location for data
//size : Item size in bytes
//count : Maximum number of items to be read
//stream : Pointer to FILE structure

//Return Value : fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. 
struct S
{
	char arr[10];
	int num;
	float sc;
};

int main()
{
	struct S s = {0};
	//二进制的形式读
	FILE*pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读文件
	fread(&s, sizeof(struct S), 1, pf);

	printf("%s %d %f\n", s.arr, s.num, s.sc);

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

4.9 sscanf

sscanf : 从一个字符串中读取一个格式化的数据

scanf : 针对标准输入流的格式化的输入语句 - stdin

fscanf : 针对所有输入流的格式化的输入语句 - stdin/文件

int sscanf( const char *buffer, const char *format [, argument ] ... );
//注意区别
int scanf( const char *format [,argument]... );
int fscanf( FILE *stream, const char *format [, argument ]... );

4.10 sprintf

sprintf : 把一个格式化的数据转换成字符串

printf : 针对标准输出流的格式化的输出语句 - stdout

fprintf : 针对所有输出流的格式化的输出语句 - stdout/文件

int sprintf( char *buffer, const char *format [, argument] ... );
//注意区别
int printf( const char *format [, argument]... );
int fprintf( FILE *stream, const char *format [, argument ]...);

sscanfsprintf 的综合示例:

struct S
{
	char arr[10];
	int age;
	float f;
};

int main()
{
	struct S s = { "hello", 20, 5.5f };
	struct S tmp = { 0 };

	char buf[100] = {0};
	//sprintf 把一个格式化的数据,转换成字符串
	sprintf(buf, "%s %d %f", s.arr, s.age, s.f);
	printf("%s\n", buf);

	//从buf字符串中还原出一个结构体数据
	sscanf(buf, "%s %d %f", tmp.arr, &(tmp.age), &(tmp.f));
	printf("%s %d %f\n", tmp.arr, tmp.age, tmp.f);

	return 0;
}

5. 文件的随机读写

5.1 fseek

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

//Moves the file pointer to a specified location.

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

//stream : Pointer to FILE structure
//offset : Number of bytes from origin
//origin : Initial position

//origin的选项:
//SEEK_CUR : Current position of file pointer
//SEEK_END : End of file
//SEEK_SET : Beginning of file

//Return Value : If successful, fseek returns 0. Otherwise, it returns a nonzero value. 
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读取文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a

	//调整文件指针
	fseek(pf, -2, SEEK_END);
	//fseek(pf, 3, SEEK_CUR);
	ch = fgetc(pf);
	printf("%c\n", ch);//e
	ch = fgetc(pf);
	printf("%c\n", ch);//f

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

5.2 ftell

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

long int ftell ( FILE * stream );
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读取文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a

	//调整文件指针
	fseek(pf, -2, SEEK_END);

	ch = fgetc(pf);
	printf("%c\n", ch);//e
	ch = fgetc(pf);
	printf("%c\n", ch);//f

	int ret = ftell(pf);
	printf("%d\n", ret);

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

5.3 rewind

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

void rewind ( FILE * stream );
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读取文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a

	//调整文件指针
	fseek(pf, -2, SEEK_END);

	ch = fgetc(pf);
	printf("%c\n", ch);//e
	ch = fgetc(pf);
	printf("%c\n", ch);//f

	int ret = ftell(pf);
	printf("%d\n", ret);

	//让文件指针回到其实位置
	rewind(pf);
	ch = fgetc(pf);
	printf("%c\n", ch);//a

	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

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

根据数据的组织形式,数据文件被称为文本文件或者二进制文件

数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件

如果要求在外存上以ASCII码的形式存储,则需要在存储前转换成ASCII码值。以ASCII字符的形式存储的文件就是文本文件

一个数据在文件中是怎么存储的呢?

字符一律以ASCII形式存储数值型数据既可以用ASCII形式存储,也可以使用二进制形式存储

如有整数10000,如果以ASCII码的形式输出到磁盘,则磁盘中占用5个字节(每个字符一个字节),而二进制形式输出,则在磁盘上只占4个字节(VS2013测试)。

测试代码:

#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;
}

7. 文件读取结束的判定

7.1 被错误使用的 feof

//Check end-of-file indicator.

int feof( FILE *stream );

//Return Value : A non-zero value is returned in the case that the end-of-file indicator associated with the stream is set. Otherwise, zero is returned.

牢记:在文件读取过程中,不能用 feof 函数的返回值直接用来判断文件的是否结束。

而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束

feof -> 确定文件读取结束的原因。先用下面的方法发现文件读取结束,再用 feof 判断结束原因。

  1. 文本文件读取是否结束,通过返回值来判定是否结束:判断返回值是否为EOF(fgetc),或者NULL(fgets)

    例如:

    fgetc 判断是否为 EOF 。正常读取的时候,返回的是读取到的字符的ASCII码值。

    fgets 判断返回值是否为 NULL 。正常读取的时候,返回存放字符串的空间起始地址。

  2. 二进制文件的读取结束判断,判断返回值是否小于实际要读的个数

    例如:

    fread 判断返回值是否小于实际要读取的个数。 返回值 < count ?

size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
//写代码把test.txt文件拷贝一份,生成test2.txt
int main()
{
	FILE* pfread = fopen("test.txt", "r");
	if (pfread == NULL)
	{
		return 1;
	}
	FILE* pfwrite = fopen("test2.txt", "w");
	if (pfwrite == NULL)
	{
		fclose(pfread); //关掉读取的文件
		pfread = NULL;
		return 1;
	}
    
	//文件打开成功
	//读写文件
	int ch = 0;
	while ((ch = fgetc(pfread)) != EOF)
	{
		//写文件
		fputc(ch, pfwrite);
	}
	
	if (feof(pfread)) //因为读取到文件末尾而停止
	{
		printf("遇到文件结束标志,文件正常结束\n");
	}
	else if(ferror(pfread)) //因为文件读取失败而停止
	{
		printf("文件读取失败结束\n");
	}

	//关闭文件
	fclose(pfread);
	pfread = NULL;
	fclose(pfwrite);
	pfwrite = NULL;

	return 0;
}

8. 文件缓冲区

ANSIC 标准采用“缓冲文件系统”处理的数据文件的,所谓缓冲文件系统是指系统自动地在内存中为程序中每一个正在使用的文件开辟一块“文件缓冲区”。从内存向磁盘输出数据会先送到内存中的缓冲区,装满缓冲区后才一起送到磁盘上。如果从磁盘向计算机读入数据,则从磁盘文件中读取数据输入到内存缓冲区(充满缓冲区),然后再从缓冲区逐个地将数据送到程序数据区(程序变量等)。缓冲区的大小根据C编译系统决定的。

没有缓冲区,读取或者写入每次数据时都会频繁打断操作系统

#include <stdio.h>
#include <windows.h>
//VS2019 WIN10环境测试
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语言在操作文件的时候,需要做刷新缓冲区或者在文件操作结束的时候关闭文件。如果不做,可能导致读写文件的问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值