How to directly access a certain part of a text fi

2019-08-24 02:33发布

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?

标签: c++ g++ seek
2条回答
乱世女痞
2楼-- · 2019-08-24 03:12

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.
查看更多
地球回转人心会变
3楼-- · 2019-08-24 03:30

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.

查看更多
登录 后发表回答