Thread: fgets ?

  1. #1
    Registered User
    Join Date
    Feb 2014
    Location
    NY
    Posts
    56

    fgets ?

    How can I make fgets stop reading when it reaches a new line? Right now it will read the new line and continue until the buffer is full.

    I was thinking something like this.
    Code:
    while(fp!='\n'){
         fgets(password, 256, fp);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You should not be comparing a FILE pointer with '\n'. It should be:
    Code:
    while (fgets(password, 256, fp)) {
        /* ... */
    }
    since fgets returns a null pointer when end of file (with nothing read) or an error is detected.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    How can I make fgets stop reading when it reaches a new line?
    A single call to "fgets()" does stop reading when it reaches a newline (unless the maximum specified number of characters has been read first, or EOF is encountered) - see here. Note that the newline is stored as part of the string, assuming there is room.

    So you can check the string for the presence of the newline to see if the entire line has been read.

    See here for more information and an example: FAQ > Get a line of text from the user/keyboard (C) - Cprogramming.com

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets
    By mesmer in forum C Programming
    Replies: 1
    Last Post: 11-25-2008, 12:37 AM
  2. fgets
    By stautze in forum C Programming
    Replies: 14
    Last Post: 03-17-2003, 08:28 PM
  3. fgets and EOF
    By PunkyBunny300 in forum C Programming
    Replies: 2
    Last Post: 02-24-2003, 01:16 AM
  4. fgets?
    By venus in forum C Programming
    Replies: 4
    Last Post: 01-24-2003, 04:58 AM
  5. fgets
    By CaN Opner in forum C Programming
    Replies: 8
    Last Post: 01-14-2003, 11:58 PM