How do I read file line by line?

This is a discussion on How do I read file line by line? within the C Programming forums, part of the General Programming Boards category; How can I read a text file like this for example: aassssssdffff aaadfffffffff aaaaaaaaddff asdddddff And count the number of ...

  1. #1
    Blurr
    Guest

    How do I read file line by line?

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

    aassssssdffff
    aaadfffffffff
    aaaaaaaaddff
    asdddddff

    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,490
    Close enough
    Code:
    #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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 09: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

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