(C语言)文件操作的详解


一、为什么要使用文件

在我们没有学习文件的知识之前,代码中的数据都是存放在内存中的,只要程序退出代码中的数据就会消失,等我们下次运行代码时就需要重新输入数据,这样就会很麻烦
这个时候我们就可以使用文件来直接把数据存放在电脑的磁盘上,做到数据的持久化

二、什么是文件

磁盘上的文件就是文件
在程序设计中,我们的文件一般有两种:程序文件和数据文件

1.程序文件

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

2.数据文件

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

3.文件名

一个文件要有一个唯一的文件标识,以便用户识别和引用
文件名包含三个部分:文件路径+文件主干+文件后缀
例如: c:\code\test.txt
在文件路径中有绝对路径和相对路径之分,这个在后面打开文件和关闭文件中有介绍

三、文件的打开和关闭

1.文件指针

在我们对文件进行一系列操作的时候都离不开文件指针
文件指针:FILE*
FILE:每个被使用的文件在内存中都开辟了一个相应的文件信息区,用来存放文件的相关信息(如文件的名字,文件的状态及文件当前的位置等)。这些信息时保存在一个结构体变量中的,该结构体类型是有系统声明的,取名FILE
FILE*:通过一个FILE的指针来维护这个FILE结构的变量,对文件进行操作

FILE* pf;//文件指针变量

pf是一个指向FILE类型数据的指针变量,也就是说,通过文件指针变量能够找到与它关联的文件

2.文件的打开和关闭

文件在读写之前应该先打开文件,在使用结束之后应该关闭文件
在C语言中规定使用fopen函数来打开文件
https://legacy.cplusplus.com/reference/cstdio/fopen/?kw=fopen

FILE * fopen ( const char * filename, const char * mode );

第一个参数filename为文件名(包括文件路径),第二个参数mode为打开方式。如果打开成功返回一个结构指针的地址,否则返回NULL
使用fclose函数来关闭文件
https://legacy.cplusplus.com/reference/cstdio/fclose/?kw=fclose
关闭成功返回0,否则返回一个非零的值
打开文件的方式如下:
在这里插入图片描述
读文件的使用

#include <stdio.h>
int main()
{
    
    
	//打开文件
	//FILE* pf = fopen(".\..\\..\\date.txt", "r");//相对路径  .表示当前路径..表示上一级路径
	//FILE* pf = fopen("G:\\summer_Classes\\2023\\text_10_15\\text_10_15\\date.txt", "r");//绝对路径
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//写文件
	
	
	//关闭文件
	fclose(pf);
	pf = NULL;

	return 0;
}

写文件的使用

int main()
{
    
    
	//打开文件
	FILE* pf = fopen("date.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//写文件
	char ch = 0;
	for (ch = 'a'; ch <= 'z'; ch++)
	{
    
    
		fputc(ch, pf);//fputc是一个字符输出函数
	}
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述

四、文件的顺序读写

在这里插入图片描述
fputc字符输出函数
https://legacy.cplusplus.com/reference/cstdio/fputc/?kw=fputc

int fputc ( int character, FILE * stream );
#include <stdio.h>
int main()
{
    
    
	char ch = 0;
	for (ch = 'a'; ch <= 'z'; ch++)
	{
    
    
		if (ch % 5 == 0)
		fputc('\n', stdout);//stdout是标准输出流  stdin是标准输入流  stderr是标准错误流
		fputc(ch, stdout);
	}
	return 0;
}

fgetc字符输入函数
https://legacy.cplusplus.com/reference/cstdio/fgetc/?kw=fgetc

int fgetc ( FILE * stream );
#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//读文件
	int ch = 0;
	while ((ch = fgetc(pf)) != EOF)
	{
    
    
		printf("%c ", ch);
	}

	fclose(pf);
	pf = NULL;
}

在这里插入图片描述
fputs文本行输出函数
https://legacy.cplusplus.com/reference/cstdio/fputs/?kw=fputs

int fputs ( const char * str, FILE * stream );
#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//写文件
	fputs("hello", pf);
	char arr[] = "ward";
	fputs(arr, pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
fgets文本行输入函数
https://legacy.cplusplus.com/reference/cstdio/fgets/?kw=fgets

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

这个函数读取的字符个数是num-1个

#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//读文件
	char arr[100] = {
    
     0 };
	fgets(arr, 3, pf);
	printf("%s ", arr);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
fprintf是格式化输出函数
https://legacy.cplusplus.com/reference/cstdio/fprintf/?kw=fprintf

int fprintf ( FILE * stream, const char * format, ... );
#include <stdio.h>
struct S
{
    
    
	float f;
	char c;
	int n;
};

int main()
{
    
    
	struct S s = {
    
     3.14f,'z',20};
	FILE* pf = fopen("date.txt", "w");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//写文件
	fprintf(pf, "%f-%c-%d", s.f, s.c, s.n);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
fscanf格式化输入函数
https://legacy.cplusplus.com/reference/cstdio/fscanf/?kw=fscanf

int fscanf ( FILE * stream, const char * format, ... );
#include <stdio.h>
struct S
{
    
    
	float f;
	char c;
	int n;
};

int main()
{
    
    
	struct S s = {
    
     0 };
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return;
	}
	//读文件
	fscanf(pf, "%f-%c-%d", &(s.f), &(s.c), &(s.n));
	printf("%f-%c-%d", s.f, s.c, s.n);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
fwrite二进制输出函数
https://legacy.cplusplus.com/reference/cstdio/fwrite/?kw=fwrite

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

size_t size是要写入的每个元素的大小
size_t count是元素个数

#include <stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	//写文件
	FILE*pf = fopen("date.txt", "wb");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//二进制的写文件
	fwrite(arr, sizeof(arr[0]), sizeof(arr)/sizeof(arr[0]), pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
fread是二进制输入函数
https://legacy.cplusplus.com/reference/cstdio/fread/?kw=fread

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

size_t size是要读出的每个元素的大小
size_t count是元素个数

#include <stdio.h>
int main()
{
    
    
	int arr[10] = {
    
    0};
	//写文件
	FILE* pf = fopen("date.txt", "rb");
	if (pf == NULL)
	{
    
    
		perror("fopen");
		return 1;
	}
	//二进制的读文件
	fread(arr, sizeof(arr[0]), sizeof(arr) / sizeof(arr[0]), pf);
	int i = 0;
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述
这里读出来的就是之前我们用fwrite写进去的二进制文件

以下两个函数虽然和文件操作关系不大,但是容易与文件操作函数混淆
sprintf是将格式化的数据转换成字符串
https://legacy.cplusplus.com/reference/cstdio/sprintf/?kw=sprintf

int sprintf ( char * str, const char * format, ... );
#include <stdio.h>
struct S
{
    
    
	float f;
	char c;
	int n;
};

int main()
{
    
    
	struct S s = {
    
     3.14f,'z',20 };
	char arr[100] = {
    
     0 };
	sprintf(arr, "%f-%c-%d", s.f, s.c, s.n);
	printf("%s\n", arr);
	return 0;
}

在这里插入图片描述
sscanf是将字符串转换为格式化的数据
https://legacy.cplusplus.com/reference/cstdio/sscanf/?kw=sscanf

int sscanf ( const char * s, const char * format, ...);
#include <stdio.h>
struct S
{
    
    
	float f;
	char c;
	int n;
};

int main()
{
    
    
	struct S s = {
    
     3.14f,'z',20 };
	char arr[100] = {
    
     0 };
	sprintf(arr, "%f-%c-%d", s.f, s.c, s.n);
	printf("%s\n", arr);

    struct S tmp = {
    
     0 };
    sscanf(arr, "%f-%c-%d", &(tmp.f), &(tmp.c), &(tmp.n));
    printf("%f\n", tmp.f);
    printf("%c\n", tmp.c);
    printf("%d\n", tmp.n);
	return 0;
}

在这里插入图片描述

五、文件的随机读写

1.fseek

根据文件指针的位置和偏移量来定义文件指针
https://legacy.cplusplus.com/reference/cstdio/fseek/?kw=fseek

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

在这里插入图片描述
stream:文件流
offset:偏移量
origin:是起始位置,有三种定位指针
返回值:
1.如果成功,fseek返回0;
2.否则,它返回一个非零值;
3.在无法查找的设备上,返回值未定义;

#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL) {
    
    
		perror("fopen");
		return 1;
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a
	ch = fgetc(pf);
	printf("%c\n", ch);//b
	ch = fgetc(pf);
	printf("%c\n", ch);//c
	ch = fgetc(pf);
	printf("%c\n", ch);//d
	要拿到当前文件指针所处位置向前偏移4个单位的字符
	fseek(pf, -4,SEEK_CUR);
	ch = fgetc(pf);
	printf("%c\n", ch);//a
	//要读取从头开始向后偏移1个单位的一个字符
	fseek(pf, 1, SEEK_SET);
	ch = fgetc(pf);
	printf("%c\n", ch);//b
	//要拿到文件流末尾向前偏移9个单位的一个字符
	fseek(pf, -9, SEEK_END);
	ch = fgetc(pf);
	printf("%c\n", ch);//a
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述

2.ftell

返回文件指针相较与起始位置的偏移量
https://legacy.cplusplus.com/reference/cstdio/ftell/?kw=ftell

long int ftell ( FILE * stream );
#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL) {
    
    
		perror("fopen");
		return 1;
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a
	ch = fgetc(pf);
	printf("%c\n", ch);//b
	ch = fgetc(pf);
	printf("%c\n", ch);//c
	ch = fgetc(pf);
	printf("%c\n", ch);//d
	int pos = ftell(pf);
	printf("pos = %d\n", pos);
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述

3.rewind

让文件指针的位置回到文件的起始位置
https://legacy.cplusplus.com/reference/cstdio/rewind/?kw=rewind

void rewind ( FILE * stream );
#include <stdio.h>
int main()
{
    
    
	FILE* pf = fopen("date.txt", "r");
	if (pf == NULL) {
    
    
		perror("fopen");
		return 1;
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);//a
	ch = fgetc(pf);
	printf("%c\n", ch);//b
	ch = fgetc(pf);
	printf("%c\n", ch);//c
	ch = fgetc(pf);
	printf("%c\n", ch);//d
	rewind(pf);
	ch = fgetc(pf);
	printf("%c\n", ch);//a
	fclose(pf);
	pf = NULL;
	return 0;
}

在这里插入图片描述

六、文本文件和二进制文件

根据数据的组织形式,数据文件被称为文本文件或者二进制文件
数据在内存中以二进制的形式存储,如果不加转换的输出到外存,就是二进制文件
如果要求在外存上以ASCII码的形式存储,则需要在存储前转换。以ASCII字符的形式存储的文件就是文本文件

七、文件读取结束的判定

被错误使用的feof
牢记:在文件读取过程中,不能用feof函数的返回值直接用来判断文件的是否结束。
而是应用于当文件读取结束的时候,判断是读取失败结束,还是遇到文件尾结束
文本文件:
如果用 fgetc() 读取,要判断 feof() 的返回值是否为EOF
如果用 fgets() 读取,要判断 feof() 的返回值是否为NULL
二进制文件:
都是使用 fread() 读取,要判断其返回值与指定读取个数的大小,如果小于实际要读的个数,就说明发生读取异常,如果等于实际要读的个数,就说明是因读取成功而结束;
对于读取异常的判断,我们考虑判断 ferror() 函数的返回值:
1.若ferrror()为真——异常读取而结束;
1.若feof()为真——正常读取到尾而结束;

八、文件缓冲区

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


猜你喜欢

转载自blog.csdn.net/2301_78373304/article/details/133841922