[英]Go to a specific line in file and read it
我有一个包含一组行的文件。 一种
文件1:
"Hello How are you"
"The cat ate the mouse"
基于用户输入的行的开头和结尾。 我想转到文件中的每一行并将其提取。
对于例子,如果用户键入1,然后17我得去1号线,有一个大小的17个字符。 他可以提供文件中的任何行号。
我从C ++文件的特定位置阅读了以下Answer Read 。 但是我不是很明白。 为什么线必须相同大小? 如果我有关于文件中每行开头和结尾的信息。 为什么我不能直接访问它?
我尝试使用以下代码,该代码的灵感来自使用Seekg从文件中的指定位置读取数据,但是为什么我无法提取这些行?
#include <fstream>
#include <iostream>
using namespace std::
void getline(int, int, const ifstream & );
int main()
{
//open file1 containing the sentences
ifstream file1("file1.txt");
int beg = 1;
int end = 17;
getline(beg,end, file1);
beg = 2;
end = 20;
getline(beg,end, file1);
return 0;
}
void getline(int beg, int end, const ifstream & file)
{
file.seekg(beg, ios::beg);
int length = end;
char * buffer = new char [length];
file.read (buffer,length);
buffer [length - 1] = '\0';
cout.write (buffer,length);
delete[] buffer;
}
该代码似乎使用行号作为字节偏移量。 如果要偏移“ 1”,则文件将向前搜索1个字节,而不是1行。 如果要偏移2,文件将向前寻找2个字节,而不是2行。
要查找特定的行,您需要读取文件并计算换行的次数,直到到达所需的行为止。 已经有执行此操作的代码,例如std::getline()
。 如果您尚不知道所需行的确切字节偏移量,则可以调用std::getline()
等于所需行号的次数。
还要记住,文件的第一个字节位于偏移量0而不是偏移量1,并且不同的平台使用不同的字节来指示行的结尾(例如,在Windows上是"\\r\\n"
,在Unix上是"\\n"
)。 如果您使用库函数读取行,则应注意行尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.