counting the number of lines in a text file

前端 未结 4 2066
无人共我
无人共我 2020-12-04 16:53

I\'m reading lines off of text file and I\'m wondering if this is a good way to go? I had to write the function numberoflines to decrease the number_of_li

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:36

    In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.

    File might look some thing like this:

    "hello 1
    "Hello 2
    
    "
    

    Code below

    #include 
    #include 
    #define FILE_NAME "file1.txt"
    
    int main() {
    
        FILE *fd = NULL;
        int cnt, ch;
    
        fd = fopen(FILE_NAME,"r");
        if (fd == NULL) {
                perror(FILE_NAME);
                exit(-1);
        }
    
        while(EOF != (ch = fgetc(fd))) {
        /*
         * int fgetc(FILE *) returns unsigned char cast to int
         * Because it has to return EOF or error also.
         */
                if (ch == '\n')
                        ++cnt;
        }
    
        printf("cnt line in %s is %d\n", FILE_NAME, cnt);
    
        fclose(fd);
        return 0;
    }
    

提交回复
热议问题