This blog is under construction

Monday 29 July 2013

C program to read a file line by line

Write a C program to read a file line by line.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        FILE *fp;
        int line = 1;
        char fileName[MAX], str[MAX];

        /* get the input file name from the user  */
        printf("Enter your input file name:");
        fgets(fileName, MAX, stdin);
        fileName[strlen(fileName) - 1] = '\0';

        /* open the input file in read mode */
        fp = fopen(fileName, "r");

        if (!fp) {
                printf("Unable to open the input file!!\n");
                return 0;
        }

        printf("\nReading the file %s line by line:\n", fileName);

        /* read the contents of the input file line by line */
        while (!feof(fp)) {
                fgets(str, MAX, fp);
                if (!feof(fp)) {
                        printf("Line %d: %s", line++, str);
                }
                strcpy(str, "\0");
        }

        /* closing the file */
        fclose(fp);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name: data.txt

  Reading the file data.txt line by line:
  Line 1: Take up one idea. Make that one idea your life -
  Line 2: think of it, dream of it, live on that idea. Let 
  Line 3: the brain, muscles, nerves, every part of your 
  Line 4: body, be full of that idea, and just leave every 

  Line 5: other idea alone. This is the way to success.






SEE ALSO

    No comments:

    Post a Comment