有没有办法请求在C 中读取文本文件的某个位置
Is there a way to request a certain location of a text file to be read in C++?
我正在使用两行的文本文件。每行上有几千个数字(签名双打(。因此看起来像这样:
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,您可以使用tellg
和seekg
来存储和还原位置。但是,我尚未证实它们与格式输入一起工作。
假设您不想将结果存储在内存中,而另一种解决方案只是两次打开文件 - 并将其视为将其视为从两个不同文件中读取行。
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- C++程序不返回文件中文本和字符串数据的值
- 提升配置文件的文本文件接收器设置
- 随机访问文件格式,用于分层组织的二进制文件和文本文件
- 是否可以使头文件使文本居中?- 在控制台中
- 如何为包含其他 protobuf 的 protobuf 文件编写文本
- 使用strtok_s显示来自文本文件的文本
- 根据某些输入文件预测文本生成'random'下一个字符
- 从二进制文件中抓取文本时,为什么 xdg_vtnr=8 是我的结果
- 我怎么知道我是在读二进制文件还是文本文件
- 如何在wxWidgets的同一窗口中拖放文件和文本
- 二进制文件到文本文件,文本文件到二进制文件
- 无法从文件打印文本
- 设置新文件默认文本
- C++显示文本文件...("Echo"文本文件)
- 从Windows应用程序的文本框中抓取文本
- 音频文件到文本使用SAPI或同等功能的SR
- 对于大文件,文本文件中的大多数常用词从未完成
- 通过套接字发送文件和文本
- 从文件读取文本到无符号字符数组