C function that counts lines in file

后端 未结 7 2047
广开言路
广开言路 2020-12-06 03:10

When I try to run my program, I get the wrong number of lines printed.

LINES: 0

This is the output although I have five lines in my .txt fi

7条回答
  •  星月不相逢
    2020-12-06 03:26

    Here is complete implementation in C/C++

    #include 
    
    void lineCount(int argc,char **argv){
    
            if(argc < 2){
                 fprintf(stderr,"File required");
                 return;
            }
            FILE *fp = fopen(argv[1],"r");
    
    
    
            if(!fp){
                fprintf(stderr,"Error in opening file");
                return ;      
            }
    
            int count = 1; //if a file open ,be it empty, it has atleast a newline char
            char temp;
    
            while(fscanf(fp,"%c",&temp) != -1){
                    if(temp == 10) count++;
            }
    
            fprintf(stdout,"File has %d lines\n",count);
       }
    
    int main(int argc,char **argv){
    
            lineCount(argc,argv);
            return 0;
    }
    https://github.com/KotoJallow/Line-Count/blob/master/lineCount.c
    

提交回复
热议问题