Method to get the number of lines in a file

  • 2020-04-01 21:32:59
  • OfStack

The first way
 
Idea: read out the characters in the file one by one and then compare them with \n.


     #include <stdio.h> 
     #include <string.h>  
     #include <errno.h>   

        
     int main(int argc, char *argv[])  
     {   
         FILE *fp;   
         int n = 0;  
         int ch;  

         if((fp = fopen(argv[1],"r+")) == NULL)  
         {  
             fprintf(stderr,"open file 1.c error! %sn",strerror(errno));  
         }  

         while((ch = fgetc(fp)) != EOF) 
         {  
             if(ch == 'n')  
             {  
                 n++;  
             } 
         }  

         fclose(fp); 
         printf("%dn",n);  
         return 0; 
     }

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/201333110407119.png" >

The second way
  Use the fgets. Fgets prototype: char *fgets(char *s, int size, FILE *stream); , fgets can read up to size-1 characters, the remaining one is reserved for \0, that is, always a bit reserved for \0. Also note: fgets stops reading when it encounters \n. If you can put \n in the array then read \n, otherwise you can only read \n next time. The rest will have to be read next time. Here's the pattern! So \n is always in the first place before \0.


     #include <stdio.h>   
     #include <string.h>   
     #include <errno.h>  

       
     int main(int argc, char *argv[])   
     {  
         FILE *fp;  
         int n = 0; 
         char buffer[3]; 

         if((fp = fopen(argv[1],"r+")) == NULL) 
         {  
             fprintf(stderr,"open file 1.c error! %sn",strerror(errno));  
         }  

         while((fgets(buffer,3,fp)) != NULL) 
         { 
             if(buffer[strlen(buffer) -1] == 'n')
             {  
                 n++; 
             }  
         }  

         fclose(fp); 
         printf("%dn",n);  
         return 0;  
     } 

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/201333110700837.png" >


Related articles: