Seekg(),fstream

------------------------------------------------------
Name: Qasim Zafar
Address: Khanewal, Block 14
Date: 26-01-2012
Destination: Lahore
Flight No: 241
Seat: 76
------------------------------------------------------
This is the text file from where I want to copy some info to some char arrays.
like Name[]; Address[];

Now I need only the last column information, my question is, is there any way through which I could get only the last column..........by using seekg();
I wouldn't use seekg(). I would read in each line in the file with a getline() and then use find() to find the ":" and then save off one plus that value to the end of the string (make sure you check boundaries). That would get you the second/last column.

http://www.cplusplus.com/reference/iostream/istream/getline
http://www.cplusplus.com/reference/string/string/find
You could seek to the end of the file and then decrement and peek() till you find a line break.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>
#include <iostream>

int main()
{
  char tmp[256] = {0};
  std::ifstream in("list.txt");
  in.seekg(0,std::ios_base::end);
  int end = in.tellg();
  int marker = end - 2; // just in case the file ends with a line break
  while(--marker)
  {
    in.seekg(marker,std::ios_base::beg);
    if(in.peek() == 0x0A || in.peek() == 0x0D)
    {
      in.seekg(++marker,std::ios_base::beg);
      in.read(tmp,end-marker+1);
      break;
    }
  }
  std::cout << tmp << std::endl;
}

you can't jump to a certain line unless all the lines have the same amount of bytes but you can ignore every line until the one you want

1
2
3
4
5
6
7
8
9
fstream& moveTo(fstream& file, int num)
{
    file.seekg(0L, ios::beg);
    for(int i=0; i < num - 1; i++)
    {
        file.ignore(numeric_limits<streamsize>::max(),'\n');
    }
    return file;
}
Topic archived. No new replies allowed.