C++,对文件的操作

据说直接提交文件内容会让代码跑的更快??(都市传说)

对文件进行操作,包括查找,储存,遍历,输出;

以本地的一个记事本当一个字典来进行实验

用到头文件:#include<fstream>

用到的函数:

记住要在打开文件之前定义一个接受文件的指针:

FILE *op;

fopen("路径","r\r+\w\w+\....");

fscanf(op,"%s....",data);//将文件内容赋值给data

fprintf(op,"%s...",data)//将data内容加入至文件;

feof(op)//判断文件结尾

fclose(op);

不说其他的了,直接上代码,代码里啥都有:

#include"header.h"

struct node{
	char English[30];
	char Chinese[30];
};

void see()
{
	cout<<"----------------------------"<<endl;
	cout<<"1.查找"<<endl;
	cout<<"2.写入"<<endl;
	cout<<"----------------------------"<<endl;
	cout<<endl;
}
/*----------------------单词查找-------------------------------------*/
void findword(char key[30])
{
	FILE *op;
	if((op=fopen("D:\\file111\\file1.txt","r+"))==NULL)//打开文件,w的话会清空该文件 的内容,我也不知道为什么。。不信的可以试试。。 
	{
		cout<<"false"<<endl;
		return ;
	}
	
	cout<<1<<endl;
	
	int num=0,f=1;
	node word[1000];
	while(f&&!feof(op))
	{
		fscanf(op,"%s\n%s\n",word[num].English,word[num].Chinese);
		if(strncmp(key,word[num].English,strlen(key))==0)
		{
			if(strlen(word[num].English)==strlen(key))
			{
				f=0;
				break;
			}
		}
		num++;
	}
	if(f)
		cout<<"no find"<<endl;
	else
		cout<<"单词:"<<word[num].English<<"中文:"<<word[num].Chinese<<endl;
	fclose(op);
}

void find()
{
	system("cls");
	cout<<"输入查找单词"<<endl;
	char word[30];
	cin>>word;
	findword(word);
}
/*-----------------------------单词记忆-------------------------------*/


void remind()
{
	cout<<"输入记忆的单词"<<endl;
	node word;
	cin>>word.English;
	cout<<"输入汉语"<<endl;
	cin>>word.Chinese;
	FILE *op;
	if((op=fopen("D:\\file111\\file1.txt","r+"))==NULL)
	{
		cout<<"false"<<endl;
		return ;
	}
	fprintf(op,"%s\n%s\n",word.English,word.Chinese);//直接存进去就行了
	fclose(op);
}


/*------------------------------------------------------------------*/
int main()
{
	int n;
	see();
	while(cin>>n&&(n==1||n==2))
	{
		system("cls");
		see();
		if(n==1)
			find();
		else
			remind();
		
	}
	
}

 
 

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/80992638