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?
#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" ;
}
}