Counting number of lines in the file in C

余生长醉 提交于 2021-02-05 07:32:05

问题


I'm writing a function that reads the number of lines in the given line. Some text files may not end with a newline character.

int line_count(const char *filename)
{
   int ch = 0;
   int count = 0;    
   FILE *fileHandle;

   if ((fileHandle = fopen(filename, "r")) == NULL) {
      return -1;
   }

   do {
      ch = fgetc(fileHandle);
      if ( ch == '\n')
         count++;
   } while (ch != EOF);

   fclose(fileHandle);

   return count;
}

Now the function doesn't count the number of lines correctly, but I can't figure out where the problem is. I would be really grateful for your help.


回答1:


fgets() reads till newline character or till the buffer is full

char buf[200];
while(fgets(buf,sizeof(buf),fileHandle) != NULL)
{
  count++;
}

fgetc() is an issue here because you encounter EOF first and exit your do while loop and never encounter a \n character so count remains untouched for the last line in your file.If it happens to be there is a single line in your file that the count will be 0




回答2:


Here is another option (other than keeping track of last character before EOF).

int ch;
int charsOnCurrentLine = 0;

while ((ch = fgetc(fileHandle)) != EOF) {
    if (ch == '\n') {
        count++;
        charsOnCurrentLine = 0;
    } else {
        charsOnCurrentLine++;
    }
}
if (charsOnCurrentLine > 0) {
    count++;
}


来源:https://stackoverflow.com/questions/29751837/counting-number-of-lines-in-the-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!