-2
* 我已經回答了我的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
}
「我不想使用,ifstream,ofstream。」你在很多地方使用它。你使用多個輸入文件? – 999k