This blog is under construction

Monday, 29 July 2013

C program to count number of lines in a file

Write a C program to count number of lines in a file.


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

  int main() {
        FILE *fp;
        int lineCount = 0;
        char filename[MAX], str[MAX];

        /* get the 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");

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

        /* calculates the number of lines in the input file */
        while (!feof(fp)) {
                fgets(str, MAX, fp);

                if (!feof(fp)) {
                        lineCount++;
                }
        }

        /* print the number of lines in input file */
        printf("Number of lines in the given file is %d\n", lineCount);

        /* close the opened file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  apple
  ball
  cat
  donkey
  elephant
  fashion

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name: data.txt
  Number of lines in the given file is 6






SEE ALSO

    No comments:

    Post a Comment