This blog is under construction

Wednesday, 31 July 2013

C program to find the number of character, words and lines in a file

Write a C program to find the number of character, words and lines in a file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256
  #define INSIDE 1
  #define OUTSIDE 0

  int main() {
        FILE *fp;
        char filename[MAX];
        int word, line, chr, ch, pos = OUTSIDE;

        word = line = chr = 0;

        /* get the input file name from the user */
        printf ("Enter your input file name:");
        scanf("%s", filename);

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

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

        /*
         * calculating the number of lines, characters
         * and word in the given input file
         */
        while ((ch = fgetc(fp)) != EOF) {
                /* no of characters */
                chr++;

                /* no of lines */
                if (ch == '\n') {
                        line++;
                }

                /* no of words maninpulation */
                if (ch == '\n' || ch == '\t' || ch == ' ') {
                        pos = OUTSIDE;
                } else if (pos == OUTSIDE) {
                        pos = INSIDE;
                        word++;
                }
        }

        /* printing the results */
        printf("No of lines: %d\n", line);
        printf("No of words: %d\n", word);
        printf("No of characters: %d\n", chr);

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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file name: library.txt
  No of lines: 4
  No of words: 16
  No of characters: 80

  jp@jp-VirtualBox:~/$ cat library.txt 
  1 Samuel 4 100.739998
  2 Raja 3 150.110001
  3 Gopi 5 175.190002
  5 Ram 1 50.150002






SEE ALSO

    No comments:

    Post a Comment