C++ 整理txt文件的小工具 对文件格式处理

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
using namespace std;


const int ID_SIZE=5;//根据相应的模式进行选择


struct DADE
{
vector<string>vctMyDateList;
};


struct MyDate
{
string strId;
DADE date;

};


bool fnIsHeadLine(string str)
{
if (str.substr(0,2)!="0x") //首选确认首行是否0x开头
{
return false;
}
else 
{
if (str.size()>=2+ID_SIZE*3) //确定ID个数是否基本吻合
{
for (int i=1;i<ID_SIZE;i++) //确定每个逗号是否都能对应上
{
string strIdent=str.substr(2+i*3-1,1);
if (strIdent==",")
{
continue;
}
else
{
return false;
}
}
return true;
}
else
{
return false;
}
}
}


string fnGetIdFromStr(string str)
{
//带0x的返回
string strResult = "";
string strNew = str.substr(2); //切除0x

for (int i=0; i<ID_SIZE; i++)
{
strResult += "0x";
strResult += strNew.substr(i*3,2);
if (i!=(ID_SIZE-1))
{
strResult += ",";
}
}
return strResult;
}


string fnGetFirstLineDate(string str)
{
string strResult = " ";
string strNew = str.substr(0,str.size()-1); //去掉最后一个空格


int iPos = strNew.find_last_of(",");
if (iPos!=string::npos)
{
strResult =strNew.substr(iPos+1);//从逗号开始取到结尾
}
return strResult;
}


void fnReadFile(vector<MyDate> &vct,string strFilename)
{
ifstream fin(strFilename.c_str());
if (fin.bad())
{
cout<<"Error when open file!"<<endl;
return;
}
string str ="";
while (getline(fin,str))
{
if (str!="")
{
if (fnIsHeadLine(str))
{
MyDate myDate;
myDate.strId=fnGetIdFromStr(str);
myDate.date.vctMyDateList.push_back(fnGetFirstLineDate(str));
vct.push_back(myDate);
}
else
{
if (vct.size()<1)
{
continue;
}
MyDate &myDate = vct[vct.size()-1];
myDate.date.vctMyDateList.push_back(str.substr(0,str.size()-1)); // 去掉最后的空格
}
}
}
fin.close();
return;
}


void fnWriteFile(vector<MyDate> &vct,string strFilename)
{
ofstream fout(strFilename.c_str());
if (fout.bad())
{
cout<<"Error when write file !"<<endl;
return;
}
for (unsigned int i=0;i<vct.size();i++)
{
fout<<vct[i].strId<<"\t"; //把这行的ID输出
for (unsigned int j=0;j<vct[i].date.vctMyDateList.size();j++) //这个容器数组进行遍历
{
fout<<"\""<<vct[i].date.vctMyDateList[j]<<"\""; //ID后面的字符依次输出
if (j!=(vct[i].date.vctMyDateList.size())-1)
{
fout<<","; //每输一个字符加逗号
}
}
fout<<"\n"; //一行输出完时加换行符
}
fout.close();
return;
}


int main(void)
{
//数据存储
vector<MyDate> vctMyDatr;
vctMyDatr.clear();


//读取数据(包括整理数据)
fnReadFile(vctMyDatr,"test.txt");




//写入数据到文件中
fnWriteFile(vctMyDatr,"new_test.txt");
return 0;
}

猜你喜欢

转载自blog.csdn.net/liuyudong_/article/details/80349531
今日推荐