print line by line from a file

This is a discussion on print line by line from a file within the C Programming forums, part of the General Programming Boards category; Hi all, I am new to C programming. I got a question here.. let say i wanna read from a ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    30

    print line by line from a file

    Hi all,

    I am new to C programming. I got a question here..

    let say i wanna read from a file sample.txt :
    hello boy
    how old are you?

    and print out line by line.

    if i use
    fscanf(file, "%s\n", line);
    printf("%s\n", line);

    the answer will be:
    hello
    boy
    how
    old
    are
    you?

    How can i print it line by line like following:
    hello boy
    how old are you?


    Thank you so much...

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    fscanf uses whitespace as a record separator. If you want to read a string with internal whitespace, you need to jump through some tricky hoops using format modifiers. It's much easier to use fgets, which uses a newline as the record separator:
    Code:
    char buffer[BUFSIZ];
    
    while (fgets(buffer, sizeof buffer, in) != NULL)
      fputs(buffer, stdout);
    My best code is written with the delete key.

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    I think you want to try fgets.

    Edit: beaten
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    Registered User
    Join Date
    Feb 2005
    Posts
    30
    Thanks Prelude and pianorain...


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File being filled with NULLs
    By Tigers! in forum Windows Programming
    Replies: 2
    Last Post: 06-30-2009, 05:28 PM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. trying to print a line from a text file
    By kryonik in forum C++ Programming
    Replies: 1
    Last Post: 06-06-2006, 09:14 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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