A function that reads from a specific point in a file?

I'm looking for a function that can read from a specified point in a file, preferably in <fstream>. Does anyone know of such a function? Here's an example of what I'm looking for (hypotheticalFunc() is the function I'm looking for):
Code:
1
2
3
4
5
6
7
8
9
ifstream indata;
char i[2];
int fileLine = 2;
indata.open("file.txt");
indata.hypotheticalFunc(fileLine, etc.);

indata >> i[0];
indata >> i[1];
cout << i[0] << i[1] << endl;


Hypothetical file:
1
2
ABCD
EFGH


Output:
EF
The function is called seekg:
http://www.cplusplus.com/reference/iostream/istream/seekg/

You can't jump to a line directly, but you can seek to a byte offset.
There are seek functions which seek to an offset. However you can't use those for this because you want to seek to a certain line number. Since lines have all varying lengths, there's no way you can just skip to a certain line number because the exact position of that line in the file depends on the lengths of all the lines before it.

So there isn't any function to do exactly what you are looking for. You will need to manually seek to a given line number on your own (or write your own function to do it).

This was brought up in another thread very recently. There's a possible solution for you there:

http://cplusplus.com/forum/general/50400/


EDIT: I'm too slow.

seekg is the seek function I was talking about. But again it will not work with line numbers. It works with file offsets.
Last edited on
closed account (DSLq5Di1)
Alternatively, indata.ignore(numeric_limits<streamsize>::max(), '\n') in a loop for however many lines you wish to skip.. you can wrap it up in a functor for added convenience,

1
2
#include <iostream>
#include <limits> 

1
2
3
4
5
6
7
8
9
10
11
12
13
class skip_lines
{
public:
    skip_lines(int n) : m_val(n) {}
    friend std::istream& operator>>(std::istream& is, const skip_lines& sl)
    {
        for (int i = 0; is.good() && i < sl.m_val; ++i)
            is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        return is;
    }
private:
    int m_val;
};

indata >> skip_lines(1) >> i[0] >> i[1];
Topic archived. No new replies allowed.