有没有办法请求在C 中读取文本文件的某个位置

Is there a way to request a certain location of a text file to be read in C++?

本文关键字:文件 取文本 位置 读取 请求 有没有      更新时间:2023-10-16

我正在使用两行的文本文件。每行上有几千个数字(签名双打(。因此看起来像这样:

X.11   X.12   X.13   ...
X.21   X.22   X.23   ...

对于我程序的每个循环,我想从每行读取一个数字。因此,对于循环的第一次迭代,它将是X.11&X.21和第二次迭代X.12&X.22等。我不需要存储值。

预期输出:

X.11  X.21
X.12  X.22
X.13  X.23

如何在C 中完成?我通常使用fstream读取文件,并使用std::getline(file, line)逐行阅读文件。我将如何从每行读取一个数字?

我不需要存储值。

当然,但是,如果您这样做,请在两个阵列的双打中说,那么您的循环是微不足道的,并且比常规磁盘读取的速度要快得多。而且,几千个双打的两个阵列可能比您想象的要少。1 MB的RAM可以包含131072八个字节双打。

我假设您需要: 我想从每行读取一个数字。
否则请评论我;我将删除答案。

并行2个流读文件

std::ifstream input_file_stream_1( "file" );
std::ifstream input_file_stream_2( "file" );
std::string line_1;
std::string line_2;
std::string ignore;
std::getline( input_file_stream_2, ignore );    // ignore the whole first line
for( ; input_file_stream_1 >> line_1 && input_file_stream_2 >> line_2; ){
    std::cout << line_1 << " and " << line_2 << 'n';
}
input_file_stream_1.close();
input_file_stream_2.close();  

输入:

X.11   X.12   X.13   ...
X.21   X.22   X.23   ...

输出:

X.11 and X.21
X.12 and X.22
X.13 and X.23
... and ...

它如何工作?
由于您的文件只有2行,因此我在同一文件上使用了两个input_stream。其中一个是第一行,另一行是第二行。但是在去循环之前。input_file_stream_2读取第一行,而无需使用它,因为input_file_stream_1想要读取此产品。因此,在忽略该行之后(第一行(。input_file_stream_1具有1行,input_file_stream_2具有第2行。现在您有两行。在for循环中,(或者(您可以通过>>操作员提取每个文本


或使用std::regex库:

std::ifstream input_file_stream( "file" );
std::string line_1;
std::string line_2;
std::getline( input_file_stream, line_1 );
std::getline( input_file_stream, line_2 );
std::regex regex( R"(s+)" );
std::regex_token_iterator< std::string::iterator > begin_1( line_1.begin(), line_1.end(), regex, -1 ), end_1;
std::regex_token_iterator< std::string::iterator > begin_2( line_2.begin(), line_2.end(), regex, -1 ), end_2;
while( begin_1 != end_1 && begin_2 != end_2 ){
    std::cout << *begin_1++ << " and " << *begin_2++ << 'n';
}
input_file_stream.close();  

输出:(如上所述(

X.11 and X.21
X.12 and X.22
X.13 and X.23
... and ...

注意:
有多种方法

如果您已经使用 std::getline(file, line)读取了行,则可以采用您获得的字符串,然后将其tokenize char* p = strtok (yourline, " ");,然后 *p在第一行中导致x.11,对于接下来,您只需再次致电strtok

对于Fstream,您可以使用tellgseekg来存储和还原位置。但是,我尚未证实它们与格式输入一起工作。

假设您不想将结果存储在内存中,而另一种解决方案只是两次打开文件 - 并将其视为将其视为从两个不同文件中读取行。