Thread: How to read previous line of file?

  1. #1
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Arrow How to read previous line of file?

    Ok, so I was wondering how would I read a previous line of a file I already read with getline(ifstream_object, buffer_str)?
    I figured seekg(-1, ios_base::cur) might work to step to the position of the previous line, but since I don't have much experience using seekg() and the reference that I read on it didn't mention how the first parameter "streampos off" is calculated (i.e. if its relative to the line read or if its relative to the character position), I figured I would ask here.
    I'm an alien from another world. Planet Earth is only my vacation home, and I'm not liking it.

  2. #2
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    The easiest way would be to store the previous line as you step through, i.e. read in the current line, and at the end of your loop store curr -> last
    Last edited by Epy; 01-20-2012 at 09:37 PM.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Obviously it's relative to the current character position, not line.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Saving the line as Epy suggests is the simplest thing.

    Or you could do -> istream::tellg - C++ Reference
    Code:
    streampos pos = fs.tellg();
    // read a line
    ...
    fs.seekg(pos, ios::beg);
    // read a line again.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 21
    Last Post: 08-07-2011, 09:55 PM
  2. Read file line by line and interpret them
    By sombrancelha in forum C Programming
    Replies: 8
    Last Post: 03-17-2011, 09:48 AM
  3. Read text file line by line and write lines to other files
    By magische_vogel in forum C Programming
    Replies: 10
    Last Post: 01-23-2011, 10:51 AM
  4. How to go to a previous line
    By Megamanenm in forum C++ Programming
    Replies: 1
    Last Post: 04-14-2009, 06:49 PM
  5. Returning to previous line
    By Garland in forum C++ Programming
    Replies: 7
    Last Post: 01-12-2008, 06:15 AM