Thread: about fgets

  1. #1
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007

    about fgets

    If i am reading from a text file using fgets, and at the end of the text there is a "\n" what options am i left with if fgets treminates at the "\n" to find the next bit of text.

    is there a way to adjust the file pointer to get me to the next line/begining of text?

    or does it go there automatically as it is a new line?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Just call fgets() in a loop.
    while ( fgets( buff, sizeof buff, fp ) != NULL )
    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.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    It's there automatically.

    char szBuffer[BUFSIZ];
    FILE fIn;
    ... /* Assume fIn is initialized and pointing to a valid file for reading. */
    fgets(szBuffer, sizeof(szBuffer), fIn);
    Now depending on the data in the file, the following could occur:

    • A '\n' will be the last character read from the file and stored in szBuffer (not counting a '\0', which is automatically appended by fgets())
    • The line length will be greater than the size of the buffer, so no '\n' will be stored, and only the first part of the line that can fit inside the buffer will be stored.
    • Something went wrong with reading (perhaps the end of the file was reached), and fgets() will return NULL. You could then figure out why it returned NULL with usage of feof(), ferror(), and such.

    In the first case, the next call to fgets() will start on the next line. Similarly, in the second case, fgets() will begin right where it left off, which was somewhere in the middle of the line. In the last case, you should not call fgets() again for that file unless you know what you're doing.

  4. #4
    Temporal Apparition qubit67's Avatar
    Join Date
    Jan 2007
    Cheers guys, thats what I needed to know

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 06:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 03:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM