[英]C++ I/O Rereading a file after EOF (was: Parsing a Comma Delimited Text File)
让我们来看看代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
string usrFileStr,
fileStr = "airNames.txt", // declaring string literal
sLine; // declaring a string obj
fstream inFile; // declaring a fstream obj
char ch;
cout << "Enter a file: ";
cin >> usrFileStr;
inFile.open( usrFileStr.c_str(), ios::in );
// at this point the file is open and we may parse the contents of it
while ( !inFile.eof() )
{
getline ( inFile, sLine ); // store contents of txt file into str Obj
for ( int x = 0; x < sLine.length(); x++ )
{
if ( sLine[ x ] == ',' )break; // when we hit a comma stop reading
//cout << sLine[ x ];
}
cout << endl;
}
while ( !inFile.eof() ) //read the file again until we reach end of file
{
// we will always want to start at this current postion;
inFile.seekp( 6L, ios::cur );
getline( inFile, sLine ); // overwrite the contents of sLine
for ( int y = 0; y < sLine.length(); y++ )
{
if ( sLine[ y ] == ',' )break; // hit a comma then goto seekp until eof
cout << sLine[ y ];
}
cout << endl;
}
inFile.clear();
inFile.close();
fgetc( stdin );
return 0;
}
我的文本文件格式类似于:
string, string andthenspace, numbers, morenumbers
看起来我无法读取文件两次。 每次检查EOF
..
第一个 while 条件有效,它给了我我需要的东西,逗号前的第一个字段,不包括逗号。
所以我第二次想,好吧,在第二次的每次迭代中,只用seekp(X, ios::cur)
函数从那里开始。
不幸的是,它不会第二次读取文件..
第一次读取 EOF 后,您可能需要清除流上的错误位。 即,以及执行查找操作。
你似乎走错了路:
FILE * file;
file = fopen ("file.txt","r");
if (file!=NULL){
while (!feof(file)) {
fscanf(file,"%s ,%s ,%s ,%s",str1,str2,str3,str4);
}
fclose (file);
};
您显然可以扩展上面的示例,我没有时间检查它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.