fgets problem

This is a discussion on fgets problem within the C Programming forums, part of the General Programming Boards category; I'm opening the /proc/hostname file and reading in the string in that file. But I need to use that string ...

  1. #1
    5|-|1+|-|34|) ober's Avatar
    Join Date
    Aug 2001
    Posts
    4,429

    fgets problem

    I'm opening the /proc/hostname file and reading in the string in that file. But I need to use that string and then append other stuff after it later, but it appears as though there is an newline character after the string. here's my code:

    Code:
    fp = fopen("/thefile", "r");
    fgets(lineBuf, count, fp);
    fclose(fp);
    and if you do a printf directly after that, it prints what is in lineBuf and then go to the next line!? anyone?

  2. #2
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    fgets stops if the newline character is encountered. It is included in the string though.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Do this after your call to fgets:
    if ( ( p = strchr ( lineBuf, '\n' ) ) != NULL ) *p = '\0';

    You find the newline and replace it with a nul.

    -Prelude
    My best code is written with the delete key.

  4. #4
    5|-|1+|-|34|) ober's Avatar
    Join Date
    Aug 2001
    Posts
    4,429
    what is p in that piece of code? Just a pointer? a char *??

  5. #5
    Has a Masters in B.S.
    Join Date
    Aug 2001
    Posts
    2,267
    i would say yes, since thats what strchr returns.
    ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >a char *??
    Yes

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with fgets....
    By Huskar in forum C Programming
    Replies: 5
    Last Post: 03-29-2009, 10:13 AM
  2. Words and lines count problem
    By emo in forum C Programming
    Replies: 1
    Last Post: 07-12-2005, 03:36 PM
  3. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  4. print problem while using fgets()
    By learninC in forum C Programming
    Replies: 12
    Last Post: 05-15-2005, 09:29 PM
  5. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21