我有一个包含许多记录的文本文件。每条记录都存储在 100 个字符长的单行中。
假设我想直接访问第 n 条记录。我可以使用 for 循环来完成,读取 n 行直到我到达记录。
但是我怎么能直接访问它呢?
如果每行正好是 100 个字符长并且行尾总是\n
(即没有\r\n
内容)并且没有空行并且人们不会将 1 个制表符用于 8 个空格等,那么您可以使用(使用 ifstream)
fin.seekg(101 * n, ios::beg); // Assume the initial record has n=0.
或(使用 FILE*)
fseek(f, 101 * n, SEEK_SET);
如果您不确定任何先决条件,请使用循环。
您可以使用seekg功能:
ifstream is("test.txt");
is.seekg ( (n-1)*100, ios::beg); // move the get pointer to the beg of nth record.