Question:

How to read text files in C

by  |  earlier

0 LIKES UnLike

Hi. Can anybody help me or tell me the code on how to read a text file line by line in C programming language?

Thanks.

 Tags:

   Report

1 ANSWERS




  1. Probably the easiest way is to use "fgets()", which reads

    a single line into a buffer.

    Because you pass in a buffer size, it will not over-run

    your buffer, which makes it *much* preferable to the

    similar-but-to-be-avoided function "gets()".

    This example does not do any error checking in order to

    be as simple as possible.  In production code, you would

    want to check for errors after both the fgets() and the

    fputs().

    #include <stdio.h>

    int

    main(int argc, char* argv[])

    {

      char buff[1000];

      while (fgets(buff, sizeof(buff)-1, stdin) != 0) {

        /* At this point, one line of text is held in "buff */

        /* For this example, simply echo it to stdout     */

        (void)fputs(buff, stdout);

      }

      return 0;

    }

    To compile and run:

      $ cc example.c

      $ a.out < /etc/hosts

      # Internet host table

      #

      127.0.0.1       localhost       loghost

      192.168.0.102   unknown # Added by DHCP

    .

    .

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions