Thread: Getting the value in the last line of a file.

  1. #1
    Registered User
    Join Date
    Dec 2014
    Location
    Philippines
    Posts
    20

    Getting the value in the last line of a file.

    Hello, I am very new to C programming. Lets assume that the program creates a number of string separated by lines. Is it possible to fgets() the last line of the file? If yes, then how? Thank you very much in advance.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Yes, by reading one line at a time until you hit the end. The string you read just before that (you did remember to store that string somewhere, right?) is the last line.

    If you're looking for a way to jump straight to the last line of a file, then no, not really. There's fseek, but it doesn't play well with text files, and walking backwards to find the newline can be difficult, depending on your OS and whether you care about portability. For Linux only, it's easy. For other OSes, not so much. There's a good explanation here: c - Using fseek to backtrack - Stack Overflow.

  3. #3
    Registered User
    Join Date
    Dec 2014
    Location
    Philippines
    Posts
    20
    Thank you very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-15-2013, 09:15 AM
  2. Replies: 6
    Last Post: 06-07-2012, 02:50 AM
  3. Replies: 21
    Last Post: 08-07-2011, 09:55 PM
  4. 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
  5. Replies: 7
    Last Post: 12-13-2010, 02:13 PM