C、C++ 文件的输入输出

FILE :是一种文件类型,也称文件指针

注意:以下程序均为在vs2013中的用法,针对其他编译器,写法略有不同,但对文件的用法都一样!

定义 : FILE *fp
fgetc(fp):从fp所指的文件读一个字符;
fputc(ch,fp):将ch字符写到文件指针变量fp所指的文件中;
fopen_s(&fp,“yy.txt”,“w”):以写的方式打开名为yy.txt的数据文件,并将返回值赋给指针变量fp;
( 此写法针对vs2013,其他编译环境下为:fp = fope(“yy.txt”,“w”) 含义相同;)

实例一:
fgetc()、fputc()、fopen_s()

#include<iostream>
using namespace std;
int main()
{
	FILE *fp=NULL;
	char ch;
	if (fopen_s(&fp,"yy.txt","w") == NULL)   //打开输出文件
	{
		cout << "failed open the file";     //判断打开文件是否出错,出错则输出出错信息
		exit(0);
	}
	ch = getchar();
	while (ch != '#')     //当用户输入‘#’时停止输入
	{
		fputc(ch,fp);
		ch = getchar();    //接收最后输入的回车符
	}
	fclose(fp);     //关闭所有文件,如果不关闭文件将会丢失数据
	return 0;
}

结果:运行此段代码时,若用户输入的数据为 Hello# ,对应根目录下产生一个名为yy.txt的文本文件,文件包含内容为“ Hello ” ;

实例二:
fgets()、fputs()
fgets(str,n,fp):从fp所指向的文件读长度为n-1的字符串存放到str中
fputs(str,fp):将str所指的字符串写到fp所指的文件中
以下题目:
将一个字符串存放在指定的文件中,通过文件将内容打印在屏幕上;

#include<iostream>
using namespace std;
int main()
{
	FILE *fp=NULL;
	char str[10];
	gets(str);    //得到一个大小为10的字符串
	if (fopen_s(&fp,"str.txt","w") == NULL)   //此时为w 
	{
		cout << "failed open the file!";    
		exit(0);
	}
	fputs(str,fp);
	fclose(fp);  //将以w方式打开的文件关闭
	if (fopen_s(&fp,"str.txt","r") == NULL)    // 注意  此时为 r 读
	{
		cout << "failed open the file";    
		exit(0);
	}
	fgets(str,10,fp);
	cout<<str<<endl;
	fclose(fp);
	return 0;
}

实例三:
fread(buffer,size,count,fp)、fwrite(buffer,size,count,fp);
fread(&curscore,sizeof(int),1,fp):从fp所指的文件读入1个字节大小问4(sizeof( int ))的数据存放curscore地址中
fwrite(score,sizeof(int),5,fp):将score数组中每组数据字节大小为4(sizeof( int ))的5个数据写到fp所指向的文件中;

以下题目:
从键盘输入5个数据,存放在指定文件中,通过文件将此组数据打印到屏幕上;

#include<iostream>
using namespace std;
int main()
{
	int score[5];
	FILE *fp=NULL;
	cout << "input data:" << endl;
	for (int i = 0; i < 5; i++)
	{
		cin >> score[i];
	}
	fopen_s(&fp,"score.txt","wb");
	if (!fp)
	{
		cout << "error!" << endl;
	}
	fwrite(score,sizeof(int),5,fp);  
	fclose(fp);
	fopen_s(&fp, "score.txt", "rb");
	int curscore;      //建一个与数据类型相同的临时变量
	while (!feof(fp))   //feof(fp) 文件末尾   判断是否位于文件末尾,是停止循环
	{
		fread(&curscore,sizeof(int),1,fp);
		cout << curscore << "\t";
	}
	putchar(10);
	fclose(fp);
	return 0;
}

结果:
当我们输入一组数据时 例如:5 2 3 4 1 ,回车之后屏幕上会出现 5 2 3 4 1;

关于文件的输入输出,暂时总结这么多,想继续了解文件相关知识可以百度更多文件相关的知识,谢谢!

猜你喜欢

转载自blog.csdn.net/weixin_43718414/article/details/85003656