64,654
社区成员
发帖
与我相关
我的任务
分享
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define LINE_LEN 1024 //每行的最大长度
#define MODIFY_TIMES 1 //修改的轮数
#define LINE_NUM 3 //总共有多少行,这个要和处理函数相对应
std::string ModifyStr0(const char * str)
{
//函数里的处理由你自己定义,根据需要设置,我这里直接返回了,以下同
std::string tstr = "This is a very good one";
return tstr;
}
std::string ModifyStr1(const char * str)
{
std::string tstr = "hello";
return tstr;
}
std::string ModifyStr2(const char * str)
{
std::string tstr = "what is test -----";
return tstr;
}
std::string ModifyStr3(const char * str)
{
std::string tstr = "This is a very good one,2";
return tstr;
}
std::string ModifyStr4(const char * str)
{
std::string tstr = "hello,2";
return tstr;
}
std::string ModifyStr5(const char * str)
{
std::string tstr = "what is test -----,2";
return tstr;
}
int main()
{
//定义函数指针数组,用来保存处理函数。其中,2为处理的次数,3为有多少行要处理
//这个是为了方便后面进行循环处理,如果不循环处理可以用独立的函数
std::string(*m_Func[2][3])(const char * str);
//初始化处理函数数组
m_Func[0][0] = ModifyStr0;
m_Func[0][1] = ModifyStr1;
m_Func[0][2] = ModifyStr2;
m_Func[1][0] = ModifyStr3;
m_Func[1][1] = ModifyStr4;
m_Func[1][2] = ModifyStr5;
int m = 0;
while(m < MODIFY_TIMES)
{
//外层循环为处理的轮数
//这个向量用来保存文件,一行一个push
vector<std::string> vFile;
vFile.clear();
//先读取文件,并调用函数进行处理,这个处理也可放到写入的时候
fstream fin;
fin.open("a.txt", ios::in);
char line[LINE_LEN];
memset(line,0,LINE_LEN);
fin.getline(line,LINE_LEN);
std::string strLine = m_Func[m][0](line);
vFile.push_back(strLine);
cout<<strLine<<endl;
int k = 1;
while(k < LINE_NUM && !fin.fail())
{
memset(line,0,LINE_LEN);
fin.getline(line,LINE_LEN);
//调用处理函数进行处理
std::string strLine = m_Func[m][k](line);
vFile.push_back(strLine);
cout<<strLine<<endl;
k++;
}
fin.close();
//把处理结果写入文件,覆盖原来的
fstream fout;
//以ios::trunc方式打开可以清空原来的数据,防止,如果是字符串变短,而有部分残留
fout.open("a.txt", ios::out|ios::trunc);
int i = 0;
while(i < vFile.size())
{
fout<<vFile[i]<<endl;
i++;
}
fout.close();
m++;
}
return 1;
}
//建立一个文件,写入了两个结构体P
int main()
{
FILE* fp=fopen("F:\\data.db", "wb+");
People p;
strcpy(p.name,"张三");
p.age=23;
fwrite(&p,1,24,fp);//24是结构大小
strcpy(p.name,"");
p.age=55;
fwrite(&p,1,24,fp);
fclose(fp);
return 0;