*我已经回答了我的 onw 问题,并且它运行正常。谁有同样的问题,请看第二个答案部分。*
我必须逐行读取一个文件,并将输出逐行存储在另一个文件中,但我无法读取所有行,它只是读取具有三个记录的一行。
或者
请告诉我如何/何时使用ifstream/ofstream
。file*
等代码中是否有任何错误。
但它不工作。
// initialization
int convertFileToSingleLine( char *p_record, char *sEor,long l);
char sEor[25]={"& 0000200222! MB00200"}; //end of record
ofstream outdata; //is it legal to initialize this here????
int main()
{
outdata.open("output.txt", ios::app); //output file
ifstream infile;
infile.open("sample.txt"); //inputfile
FILE *p_record=NULL;
char buf[4000];
long int lineC;
string line;
while (getline(infile, line))
{
lineC++;
}
lineC = 3 * lineC - 2; // every line has three records, first and last are header and footer
cout << lineC; //in my case file is having 20019 records
p_record = fopen("SWITCH.txt","r"); //input file for file pointer
for(int l = 1; l <= lineC; l++)
{
while ((fgets(buf, sizeof buf, p_record)) != NULL)
{
convertFileToSingleLine(buf, sEor, lineC);
}
}
fclose(p_record);
return 0;
}
int convertFileToSingleLine(char *sInFile, char *sEor, long lC) //convert into single line
{
//ofstream outdata;
//outdata.open("output.txt", ios::app);
char sTemp[1087] = "\0";
FILE *fpIn=NULL, *fpOut=NULL;
static long int l = 0;
char *ch = NULL;
char *ch1 = NULL;
//int l=0;
try
{
static int pos=0;
int c;
//outdata<<"HI TO";
while(l!=lC)
{
if( (ch=strstr(sInFile+pos, "001")) != NULL)
{
//if((ch1=strstr(ch, "& 00002! AB00200"))!=NULL)
//{
strncpy(sTemp, ch, 1086); //one record is 1086 charater long
//}
pos = pos + 1086; //move to next position in one line, by 1086 chacters.
outdata << sTemp;
}
l++;
}
return 0;
}
catch(char *str1)
{
cout << "ERROR while opening" << sInFile << endl;
}
return 0;
}
它只读取一行,读取第一条记录两次,然后读取第二条记录。我需要整个文件。我必须删除那些 ifstream 和 ofstream,是他们的另一种方式。
**sample file:**
{
three records in one line:
002 ahjfdghfuisyguigeuihgjkgfjkbjbgjbfggfdbjbhj & 00002! AB00200 001 uyrugjnbfhdgyudgfshdfj & 00002! AB00200 001 ytygfhvghghjbv uhruighvluhjkl heuifhuihfuh & 00002! AB00200
001 jhsdjkagfdsf .....
}
output:=>
{
001 uyrugjnbfhdgyudgfshdfj & 00002! AB00200
001 uyrugjnbfhdgyudgfshdfj & 00002! AB00200
001 ytygfhvghghjbv uhruighvluhjkl heuifhuihfuh & 00002! AB00200
}