0

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?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
neuromancer
  • 53,769
  • 78
  • 166
  • 223

2 Answers2

4

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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

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.
codaddict
  • 445,704
  • 82
  • 492
  • 529