How to directly access a certain part of a text file in g++?

送分小仙女□ 提交于 2019-12-12 02:39:15

问题


I have a text file containing a number of records. Each record is stored on a single line that is 100 characters long.

Let's say I want to directly access the nth record. I could do it using a for loop, reading in n lines until I get to the record.

But how could I access it directly?


回答1:


If the each line is exactly 100 characters long and the line ending is always \n (i.e. no \r\n stuff) and there's no blank lines and people won't use 1 tab for 8 spaces etc. you can use (with ifstream)

fin.seekg(101 * n, ios::beg);  // Assume the initial record has n=0.

or (with FILE*)

fseek(f, 101 * n, SEEK_SET);

If you are unsure of any of the preconditions, use a loop.




回答2:


you can make use the the seekg function:

ifstream is("test.txt");
is.seekg ( (n-1)*100, ios::beg); // move the get pointer to the beg of nth record.


来源:https://stackoverflow.com/questions/2514158/how-to-directly-access-a-certain-part-of-a-text-file-in-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!