开发者

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

开发者 https://www.devze.com 2022-12-24 10:44 出处:网络
I have a text file containing a number of records. Each record is stored on a single line that is 100 characters long.开发者_开发技巧

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?


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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消