How to use seekg

How do you use seekg to retrieve data from a specific line in a binary file? Lets say I want to read the third line in the file, I know I can't do seekg(3,'\n')

Do I have to multiply 3 by the current position of the pointer?
To read specific lines (lines separated by new line characters), open the file in text mode.

Something like this, perhaps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <fstream>

// note: line_number is one-based (the first line in the file has line_number 1)
std::istream& read_line( std::istream& stm, std::string& line, std::size_t line_number )
{
    if( line_number == 0 ) // zero is an invalid line number
    {
        stm.clear( std::ios::failbit ) ; // put the stream into a failed state
        line.clear() ; // clear the contents of the string
        return stm ;
    }

    stm.clear() ; // clear a possible failed/eof state
    stm.seekg(0) ; // seek to the beginning of the stream

    // try to read the first line_number-1 lines from the file
    for( std::size_t i = 0 ; i < line_number-1 && std::getline( stm, line ) ; ++i ) ;
    // std::getline( stm, line ) would put the stream into a failed state
    // if 'line_number' is more than the number of lines in the file

    // if the stream isnot in a failed state (if all lines before line 'line_number' were successfully read)
    if(stm) std::getline( stm, line ) ; // read in the required line

    return stm ;
}

int main()
{
    std::ifstream file(__FILE__) ; // open this file for input

    for( std::size_t line_num : { 19, 0, 3, 92, 6 } )
    {
        std::string line ;
        if( read_line( file, line, line_num ) ) std::cout << "line #" << line_num << ":\n" << line << "\n\n" ;
        else std::cerr << "*** error: there is no line #" << line_num << " in the file.\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/e953fe4e2a5c7260
I have no idea why the seek/tell functions are specified to get ruined by text mode.
Topic archived. No new replies allowed.