register72
By: a guest | Jul 5th, 2009 | Syntax:
C++ | Size: 1.95 KB | Hits: 6 | Expires: Never
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string& trim(string &str)
{
int i,j,start,end;
//ltrim
for (i=0; (str[i]!=0 && str[i]<=32); )
i++;
start=i;
//rtrim
for(i=0,j=0; str[i]!=0; i++)
j = ((str[i]<=32)? j+1 : 0);
end=i-j;
str = str.substr(start,end-start);
return str;
}
int main(int argc, char* argv[])
{
if(argc!= 3)
{
cout<<"Usage ldifclean inputfile outputfile"<<endl;
return 0;
}
ifstream ifile;
ofstream ofile;;
ifile.open(argv[1]);
if(ifile.is_open()!=true)
{
cout<<"Cannot open inputfile "<<argv[1]<<endl;
return 0;
}
ofile.open(argv[2]);
if(ofile.is_open()!=true)
{
cout<<"Cannot open outputfile "<<argv[2]<<endl;
return 0;
}
std::string line;
std::string prevvalue="";
std::string prevattribute="";
std::string value="";
std::string attribute="";
int coloncount=0;
bool firstline=true;
while(!ifile.eof())
{
//We have a new (attribute:value) pair, write down the previous one
if(coloncount==2)
{
ofile<<prevattribute<<":"<<prevvalue<<endl;
prevattribute=attribute;
prevvalue=value;
coloncount=1;
}
getline(ifile,line);
//Empty line: end of the old entry and beginning of a new one
if(line.length()==0)
{
ofile<<prevattribute<<":"<<prevvalue<<endl;
ofile<<endl;
prevvalue="";
prevattribute="";
firstline=true;
coloncount=0;
continue;
}
string::size_type colonfound =line.find_first_of(":");
if(colonfound==string::npos)
{
//We are on a broken line. Accumulate the value
prevvalue=prevvalue.append(trim(line));
continue;
}
attribute=line.substr(0,colonfound);
value=line.substr(colonfound+1,line.length()-colonfound-1);
coloncount++;
if(firstline==true)
{
prevattribute=attribute;
prevvalue=value;
firstline=false;
}
}
return 0;
}