• Source
    1. #include <stdio.h>
    2.  
    3.  
    4.  
    5. int main()
    6.  
    7. /* Ask for a filename and count number of lines in the file*/{
    8.  
    9. //a pointer to a FILE structure
    10.  
    11. FILE *fp;
    12.  
    13. int no_lines = 0;
    14.  
    15. //consider 40 character string to store filename
    16.  
    17. char filename[40], sample_chr;
    18.  
    19. //asks user for file name
    20.  
    21. printf("Enter file name: ");
    22.  
    23. //receives file name from user and stores in a string named 'filename'
    24.  
    25. scanf("%s", filename);
    26.  
    27. //open file in read mode
    28.  
    29. fp = fopen(filename, "r");
    30.  
    31. //get character from file and store in sample_chr
    32.  
    33. sample_chr = getc(fp);
    34.  
    35. while (sample_chr != EOF) {
    36.  
    37. //Count whenever sample_chr is blank (new line) is encountered
    38.  
    39. if (sample_chr == '')
    40.  
    41. {
    42.  
    43. //increment variable 'no_lines' by 1
    44.  
    45. no_lines=no_lines+1;
    46.  
    47. }
    48.  
    49. //take next character from file.
    50.  
    51. sample_chr = getc(fp);
    52.  
    53. }
    54.  
    55. fclose(fp); //close file.
    56.  
    57. printf("There are %d lines in %s
    58.  
    59. ", no_lines, filename);
    60.  
    61. return 0;
    62.  
    63. }