Search code examples
c++fileioposition

Set start and finish limits to read from file


I need to read data from a txt file. Data I need starts in the some position in file and ends in the other position(not in the end). I know how to change start position (fin.seekg(startPos);), but how to set my finish position? I have a limit numbers, say start read at 100 position from begin and stop in 30 from end.


Solution

  • You can use fin.tellg like this:

    fin.seekg(0, fin.end);
    length = fin.tellg();
    

    to count the total number of 'positions' in the file. Then go to the desired start position and get input until the number of positions minus 30. Complete sample:

    int startPos = 100, length;
    string input;
    ifstream fin("file.txt");
    
    fin.seekg(0, fin.end);
    length = fin.tellg();
    fin.seekg(startPos);
    
    for (int i = startPos; i <= length - 30; i++) {
        getline(fin, input, '\n')
        //do something with 'input'
    }
    
    fin.close();