C function that counts lines in file

后端 未结 7 2030
广开言路
广开言路 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:34

    Here is my function

    char *fileName = "input-1.txt";
    countOfLinesFromFile(fileName);
    
    void countOfLinesFromFile(char *filename){
    FILE* myfile = fopen(filename, "r");
    int ch, number_of_lines = 0;
    do
    {
        ch = fgetc(myfile);
        if(ch == '\n')
            number_of_lines++;
    }
    while (ch != EOF);
    if(ch != '\n' && number_of_lines != 0)
        number_of_lines++;
    fclose(myfile);
    printf("number of lines in  %s   = %d",filename, number_of_lines);
    

    }

提交回复
热议问题