0
点赞
收藏
分享

微信扫一扫

简述C语言文件操作

捌柒陆壹 03-24 22:30 阅读 2

 

目录

为什么要使用文件?

文件 

 程序文件

 数据文件

文本文件

二进制文件

 文件名

⽂件的打开和关闭

流和标准流

一图 KO 流 概念

 标准流

文件指针 

 文件的打开和关闭

文件的打开模式

文件的顺序读写

文件顺序读写函数

函数原型

 一个数据在内存中怎么储存的呢? 

fputc 

文件的随机读写

fseek

ftell

rewind 




 


 

⽂件的打开和关闭

流和标准流

一图 KO 流 概念

 标准流

C语⾔程序在启动的时候,默认打开了3个流:

 


文件指针 

运行程序时,默认打开了这三个流,我们使⽤scanf、printf等函数就可以直接进行输入输出操作的。

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

 

 文件的打开和关闭

 

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


 

函数使用

#include<stdio.h>

int main()
{
	//文件指针变量读写文件
	// 当前文件位置
	//FILE* pf = fopen("data.txt", "w");

	//当前文件位置
	FILE* pf = fopen("./data.txt", "w");


	//当前文件的上一级位置
	//FILE* pf = fopen("./../data.txt", "w");

	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

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

 

文件的顺序读写

文件顺序读写函数

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

函数原型


 

int main()
{
	int a = 100;

	//文件指针变量打开文件
	FILE* pf = fopen("Data.txt", "wb");

	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//以二进制方式写入文件
	fwrite(&a, 4, 1, pf);

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

	return 0;
}

 内存中以二进制显示:


 

int main()
{
	//文件指针打开文件
	FILE* pf = fopen("Data.txt", "w");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//输入数据读写文件:26个字母
	//int i = 0;
	//for (i = 0; i < 26; i++)
	//{
	//	fputc('a' + i, pf);
	//	fputc('\n', pf);
	//}
	
	//控制台输出stdout
	int i = 0;
	for (i = 0; i < 26; i++)
	{
		fputc('a' + i, stdout);
		fputc('\n', stdout);
	}

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

 

文件的随机读写

函数使用

int main()
{
	//文件指针打开文件
	FILE* pf = fopen("Data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//读写文件
	int ch = fgetc(pf);
	printf("%c\n", ch);

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

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

	fseek(pf, 3, SEEK_SET);
	ch = fgetc(pf);
	printf("%c\n", ch);

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

 

控制台显示

 


int main()
{
	//文件指针打开文件
	FILE* pf = fopen("Data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//读写文件
	int ch = fgetc(pf);
	printf("%c\n", ch);

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

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

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


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

 

 控制台显示


 

rewind 

函数介绍

作用:返回文件起始位置(文件开头)

函数使用

int main()
{
	//文件指针打开文件
	FILE* pf = fopen("Data.txt", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//读写文件
	int ch = fgetc(pf);
	printf("%c\n", ch);

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

	rewind(pf);

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

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

 

控制台输出


举报

相关推荐

0 条评论