Thread: How do I read file line by line?

  1. #1

    How do I read file line by line?

    How can I read a text file like this for example:


    And count the number of lines in the file?

    My idea is:

    while(fgets ! eof)
    read a line
    linecount ++

    I guess what I'm getting at is, what does fgets return after it reads one line and how can you set it in a loop to read an entire file? Thanks in advance for any advice

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Close enough
    #include <stdio.h>
    int main ( ) {
        char buff[BUFSIZ];
        FILE *fp = fopen( "file.txt", "r" );
        while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
            // whatever
        fclose( fp );
        return 0;
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  3. getline function to read 1 line from a text file
    By kes103 in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2004, 06:21 PM
  4. how can i read i line from a file
    By condorx in forum C Programming
    Replies: 2
    Last Post: 05-07-2003, 02:47 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM