C语言文件操作

1. 什么是文件

磁盘上的文件是文件,在程序设计中文件分为两种:程序文件和数据文件

1.1 程序文件

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

1.2 数据文件

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

1.3 文件名

文件名是文件的唯一标识,包括文件路径+文件名主干+文件后缀。例如:c:codetest.txt

1.4 文件类型

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

数据在内存中以二进制的形式存储,①如果不加转换直接输出到外存,就是二进制文件②如果在存储前转换成ASCII码的形式输出到外存就是文本文件。

字符一律以ASCII码形式存储

数值型数据可以以ASCII形式存储,也可以使用二进制形式存储。根据文件读写函数而定。

例如10000如果以ASCII码形式存储,需要占5个字节

#include<stdio.h>
int main()
{
	FILE * pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fputs("10000", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

 

以二进制输出,则在磁盘上只占4个字节(整型变量大小)

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

 

 (小端存储)

2. 文件的打开和关闭

2.1 文件指针

文件指针指向相应的文件信息区(存放文件相关信息),文件信息存放在一个结构体变量中,该结构体类型是由系统声明的,类型是FILE。

一般我们创建一个类型为FILE*的文件指针,通过文件指针变量就能够找到与他关联的文件。

2.2 文件的打开和关闭—fopen函数和fclose函数

FILE *  fopen(const char * filename, const char * mode);      int fclose(FILE * stream);

其中mode是指打开文件的方式,如下表所示:

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

应用实例1:

相对路径:当前路径

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");//没有写路径,表示当前路径下
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world", pf);
	fclose(pf);
    pf = NULL;
	return 0;
}

相对路径:当前路径的其他文件夹

#include<stdio.h>
int main()
{
	FILE* pf = fopen(".\\Debug\\test.txt", "w");//表示当前路径下的Debug文件中的test.txt文件
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world", pf);
	fclose(pf);
    pf = NULL;
	return 0;
}

相对路径:上级文件夹中的文件夹

#include<stdio.h>
int main()
{
	FILE* pf = fopen("..\\Debug\\test.txt", "w");//表示上级文件夹中的Debug文件夹中的test.txt
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world", pf);
	fclose(pf);
    pf = NULL;
	return 0;
}

3. 文件的顺序读写

C语言只要运行起来,就会默认打开3个流

1. 标准输入流stdin(类型FILE*)

2. 标准输出流stdout(类型FILE*)

3. 标准错误流stderr(类型FILE*)

读写函数:

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

3.1 fputc函数

int fputc ( int character, FILE * stream );

stream可以是标准输出流也可以是文件流

例1:输出到文件流

#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	int i = 0;
	for (i = 0; i < 26; i++)
	{
		char ch = 'a' + i;
		fputc(ch, pf);//文件流,将26个英文字母存进文件
	}
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;

}

 例2:输出到标准输出流(屏幕)

#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	int i = 0;
	for (i = 0; i < 26; i++)
	{
		char ch = 'a' + i;
		fputc(ch, stdout);//输出到屏幕
	}
	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;

}

 

 3.2 fgetc函数

int fgetc ( FILE * stream );

例1:从文件中读

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int i = 0;
	for (i = 0; i < 26; i++)
	{
		int c = fgetc(pf);
		printf("%c ", c);
	}
	return 0;
}

例2:从标准输入流(键盘)读

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int i = 0;
	for (i = 0; i < 26; i++)
	{
		int c = fgetc(stdin);
		printf("%c ", c);
	}
	return 0;
}

3.3 fputs函数

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

例1:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fputs("hello world", pf);
	fputs("hello bit", pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

3.4 fgets函数

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

从stream中读取num-1个字符存到str指向的空间里,如果遇到换行符停止,换行符也被当作有效字符存入str中,读取完后会自动他在str末尾添加终止符‘\0’

例1:

int main()
{
	FILE* pf = fopen("test.txt", "r");
	char arr[20] = "xxxxxxxxxxxxxxxxxxxx";
	fgets(arr, 10, pf);//最多读9个
	printf("%s", arr);
	return 0;
}

3.5 fprintf函数

fprintf函数:适用于所有输出流的格式化(%d,%f...)输出函数

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

printf函数:向标准输出流写格式化数据

int printf ( const char * format, ... );

sprintf函数:向字符串写入转换成字符的格式化的数据、

int sprintf ( char * str, const char * format, ... );

例1:向文件流输出

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 10,3.14f };//3.14默认是double类型数据,3.14f将其转化为float类型
	FILE* pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fprintf(pf, "%d %f", s.a, s.s);
	fclose(pf);
	pf = NULL;
	return 0;
}

例2:向标准输出流输出

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 10,3.14f };
	FILE* pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fprintf( stdout,"%d %f", s.a, s.s);
    //printf( "%d %f", s.a, s.s);//与上面效果相同
	fclose(pf);
	pf = NULL;
	return 0;
}

例3:向字符串输出

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 10,3.14f };
	char arr[20] = { 0 };
	sprintf(arr,"%d %f", s.a, s.s);
	printf("%s", arr);
	return 0;
}

3.6 fscanf函数

fscanf函数:适用于所有输入流的格式化(%d,%f...)输入函数

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

scanf函数:适用于标准输入流的格式化(%d,%f...)输入函数

int scanf ( const char * format, ... );

sscanf函数:从字符串读取格式化的数据

int sscanf ( const char * s, const char * format, ...);

例1:从文件流输入(读)数据

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 0 };
	FILE* pf = fopen("test.txt", "r");
	fscanf(pf, "%d %f", &s.a, &s.s);
	printf("%d %f", s.a, s.s);
	return 0;
}

例2:从标准输入流读数据

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 0 };
	FILE* pf = fopen("test.txt", "r");
	fscanf(stdin, "%d %f", &s.a, &s.s);
	//scanf("%d %f", &s.a, &s.s)//结果同上
	printf("%d %f", s.a, s.s);
	return 0;
}

例3:从字符串读数据

struct S
{
	int a;
	float s;
};
int main()
{
	struct S s = { 10,3.14f };
	char arr[20] = { 0 };
	struct S tem = { 0 };
	sprintf(arr, "%d %f", s.a, s.s);//向arr输出数据
	sscanf(arr, "%d %f", &tem.a, &tem.s);//从arr读取数据放入tem
	printf( "%d %f", tem.a, tem.s);//打印tem到屏幕
	return 0;
}

3.7 fwrite函数

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

从ptr指向的位置开始,将count个大小为size个字节的元素以二进制的形式输出到stream

#include<stdio.h>
int main()
{
	FILE* pf = fopen("data.dat", "wb");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int arr[10] = { 1,2,3,4,5,6,7,8,9,0 };
	fwrite(arr, 4, 10, pf);
	fclose(pf);
	pf = NULL;
	return 0;
}

 3.8 fread函数

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

从stream中将count个大小为size个字节的元素以二进制的提取输入到ptr指向的空间

#include<stdio.h>
int main()
{
	FILE* pf = fopen("data.dat", "rb");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int tem[10] = { 0 };
	fread(tem, 4, 10, pf);
	return 0;
}

4. 文件的随机读写

文件的随机读写是指在指定的位置读写数据

4.1 fseek函数

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

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

origin有三个取值:

ConstantReference position
SEEK_SETBeginning of file(文件起始位置)
SEEK_CURCurrent position of the file pointer(文件指针当前位置)
SEEK_ENDEnd of file *(文件尾位置)

例1:

#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "w");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fputs("abcd;;gh", pf);//文件中放置abcd;;gh
	fseek(pf, 4, SEEK_SET);//从文件初始位置开始偏移4个字节定位文件指针
	fputc('e', pf);//文件被更改为abcde;gh,然后pf向后移
	fseek(pf, 1, SEEK_CUR);//从文件指针当前位置开始偏移1个字节定位文件指针
	fputc('f', pf);//文件被更改为abcde;fh

	fclose(pf);
	pf = NULL;
	return 0;
}

执行fputc('f', pf)后,pf指着还回向后移一个字节。

 4.2 ftell函数

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

long int ftell ( FILE * stream );
//计算一个文本文件中有多少个字节
#include<stdio.h>
int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	fseek(pf, 0, SEEK_END);//将文件指针指向文件末尾
	int size = ftell(pf);//计算文件指针与文件起始位置的偏移量就是文件中的字节数
	fclose(pf);
	pf = NULL;
	printf("size of test.txt = %d", size);
	return 0;
}

 4.3 rewind函数

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

void rewind ( FILE * stream );

例1:假设test.txt文件中放的是abcdef

int main()
{
	FILE* pf = fopen("test.txt", "r");
	if (NULL == pf)
	{
		perror("fopen");
		return 1;
	}
	int ch = fgetc(pf);//读取字符a,pf向后移动
	printf("%c\n", ch);//打印a
	ch = fgetc(pf);//读取字符b,pf向后移动
	printf("%c\n", ch);//打印b
	ch = fgetc(pf);//读取字符c,pf向后移动
	printf("%c\n", ch);//打印c

	rewind(pf);//文件指针回到初始位置
	ch = fgetc(pf);//读取字符a,pf向后移动
	printf("%c\n", ch);//打印a
    fclose(pf);
    pf = NULL;
	return 0;
}

5 文件结束判定

如何判定文件读取是否结束?

5.1 文本文件读取结束判定

1. fgetc函数返回值是否为EOF

2. fgets函数返回值是否为NULL

5.2 二进制文件读取结束判定

fread函数返回值是否小于实际要读的个数

5.3 判断文件读取结束原因的函数feof和ferror

feof(FILE * stream)== 1表示文件读取到最后导致读取结束

ferror(FILE * stream) == 1 表示文件读取错误而导致读取结束

例1 文本文件读取结束原因判定

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int c;
	FILE* pf = fopen("test.txt", "r");
	if (!pf)
	{
		perror("fopen");
		return 1;
	}
	while ((c = fgetc(pf))!= EOF)
	{
		putchar(c);
	}
	if (ferror(pf))
		puts("I/O error when reading");
	else if (feof(pf))
		puts("End of file reached successfully");
	return 0;
}

例2 二进制文件读取错误原因判定

#include<stdio.h>
enum {SIZE = 5};
int main()
{
	double a[SIZE] = { 1.0,2.0,3.0,4.0,5.0 };
	double b = 0.0;
	FILE* pf = fopen("data.bin", "wb");
	if(!pf)
	{
		perror("fopen");
		return 1;
	}
	fwrite(a, sizeof(*a), SIZE, pf);
	fclose(pf);
	pf = NULL;
	pf = fopen("data.bin", "rb");
	if (!pf)
	{
		perror("fopen");
		return 1;
	}
	while (fread(&b, sizeof(b), 1, pf) >= 1)
	{
		printf("%lf\n", b);
	}
	if (feof(pf))
		puts("End of file reached successfully");
	else if(ferror(pf))
		puts("I/O error when reading");

	return 0;
}

完结,撒花!🌸🌸🌸

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值