既然是C++,最好把readLine这个封装到类里面,我图省事写成全局的了。
#include
using namespace std;
int readLine(FILE *fp, char **buf, int *bufsize)
{
char * newbuf = 0;
int offset = 0;
int len = 0;
if(*buf == 0)
{
*buf = new char[128];
if(!*buf)
{
return -2;
}
*bufsize = 128;
}
while(1)
{
if(!fgets(*buf + offset, *bufsize - offset, fp))
{
return (offset != 0) ? 0 : (ferror(fp)) ? -2 : -1;
}
len = offset + (int)(strlen(*buf + offset));
if((*buf)[len - 1] == '\n')
{
(*buf)[len - 1] = 0;
return 0;
}
offset = len;
newbuf = new char[*bufsize * 2];
if (!newbuf)
{
return -2;
}
strcpy(newbuf, *buf);
delete[] *buf;
*buf = newbuf;
newbuf = 0;
*bufsize *= 2;
}
return 0;
}
int main()
{
FILE * infile = fopen("infile", "r");
if (infile == 0)
{
cout << "Open the infile failed!" << endl;
return -1;
}
FILE * outFile = fopen("outfile", "w");
if (outFile == 0)
{
cout << "Create the outFile failed!" << endl;
return -1;
}
char *line = 0;
int lineSize = 0;
while (readLine(infile, &line, &lineSize) == 0)
{
string strLine = line;
int firstSpacePos = strLine.find(" ", 0);
int secondSpacePos = strLine.find(" ", firstSpacePos + 1);
string firstName = strLine.substr(0, firstSpacePos);
string middle = strLine.substr(firstSpacePos + 1, secondSpacePos - firstSpacePos - 1);
string lastName = strLine.substr(secondSpacePos + 1, strLine.size() - secondSpacePos - 1);
string outLine = lastName;
outLine += ",";
outLine += firstName;
outLine += " ";
outLine += middle;
outLine += "\n";
fwrite(outLine.c_str(), sizeof(char), outLine.size(), outFile);
}
delete[] line;
fclose(infile);
fclose(outFile);
return 0;
}