#include <iostream>
#include<fstream>
#include<string>
#include <algorithm>
using namespace std;
int GetLineNumber(char file[],char data[],int number)//文本的总行数
{
int line=0;
ifstream infile;
infile.open(file,ios::in);
while(!infile.eof())
{
infile.getline(data,1000);
line++;
}
cout<<"find lines: "<<line<<endl;
infile.close();
return line;
}
void inPut_filedata(char file[],char data[])//给文件输入内容
{
ofstream infile;
infile.open(file,ios::app|ios::out);
infile<<data<<endl;
infile.close();
}
void output_filedata(char file[])//文件内容输出
{
ifstream infile;
char data[1000];
int line=1;
infile.open(file,ios::in);
while(!infile.eof())
{
infile.getline(data,1000);
cout<<line<<":"<<data<<endl;
line++;
}
infile.close();
}
void findstr(char file[],char find[])//查找文件中的内容
{
int line=0,LEN=1000;
char data[LEN];
ifstream infile;
infile.open(file,ios::in);
cout<<"input you find str"<<endl;
cin >>find;
while(!infile.eof())
{
infile.getline(data,1000);
if(strstr(data,find))
{
line--;
cout<<"line number: "<<line<<" "<<data<<endl;
}line++;
}
infile.close();
if(GetLineNumber(file,data,LEN)==line)
{
cout<<"Did not find, last line is "<<line<<endl;
}
}
void clearnFile(char filename[])//清除文件内容
{
ofstream outfile;
outfile.open(filename,ios::trunc);
outfile.close();
}
int main() {
char find[100];
char filename[100];
char data[100];
char choose_function[100];
while(1)
{
cout<<"*****************input file name ********************************"<<endl;
cin.getline(filename,100);
cout<<"*****************choose function *******************"<<endl;
cout<<"-----------------input -------------------"<<endl;
cout<<"-----------------output -------------------"<<endl;
cout<<"-----------------find -------------------"<<endl;
cout<<"-----------------clean -------------------"<<endl;
cin.getline(choose_function,100);
if(strstr("input",choose_function))
{
cout<<"*******************input you want to save data ******************"<<endl;
while(1)
{
cin.getline(data,100);
if(strstr("exit",data)) break;
inPut_filedata(filename,data);
}
}
else if(strstr("output",choose_function))
{
cout<<"*******************output file data :"<<filename<<"******************"<<endl;
output_filedata(filename);
}
else if(strstr("find",choose_function))
{
findstr(filename,find);
}
else if(strstr("clean",choose_function))
{
clearnFile(filename);
}
else cout<<"choose input err!"<<endl;
}
return 0;
}