-2

I recently write a piece of code that count the number of lines in a text file, however, something the while loop part just don't work properly and loop forever. Anyone can help me to find out what is the problem with that piece of code?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *fp;
int main() {
    fp=fopen("C:\\Users\\Alan\\Desktop\\text.txt","r");
    int i=0;
    while(!feof(fp)){
        i++;
    }
    fclose(fp);
    printf("The Number Of Sentence In That File: %d",i);
    getch();

}
Program5284
  • 225
  • 1
  • 2
  • 6

3 Answers3

2

The problem is that there is no advance by calling feof(fp), so the execution halts at the beggining of the file. You need to explicitly call something like, getchar(), fscanf(), fgetc(), etc. Here is an example

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

FILE *fp;
int main() {
    fp=fopen("test.txt","r");
    int i=0, ch=0;

    while((ch = fgetc(fp)) > 0){
        if(ch == '\n') 
            i++;          
    }
    fclose(fp);
    printf("The Number Of Sentence In That File: %d\n",i);
    getchar();
}
stelios
  • 2,679
  • 5
  • 31
  • 41
1

For what you want you can try something like this -

 char *s;
 s=malloc(255);
 while(fscanf(fp,"%254s",s)==1)
 {
    i++;
 }
 ...
 free(s);

This will give desired output.

Also -

 while(!feof(fp))

feof to control loop is always wrong .And you should never use feof in loop . Refer here

Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

Your loop does not terminate because you are not doing anything with the file within the loop.

Instead of using feof to control the loop, I would propose to use getline().

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

FILE *fp;
int main() {
    fp=fopen("C:\\Users\\Alan\\Desktop\\text.txt","r");

    int i = 0;
    char *line = NULL;
    size_t len = 0;

    while (getline(&line, &len, fp) != -1)
        i++;

    free(line);
    fclose(fp);
    printf("The Number Of Sentence In That File: %d\n",i);
}

Note: In this case line is set to NULL and len is set 0, hence getline() will allocate a buffer for storing the line. This buffer should be freed before the program returns.

Update

You can use the return value of getline, if you also want to know the number of chars in the file:

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

FILE *fp;
int main() {
    fp=fopen("C:\\Users\\Alan\\Desktop\\text.txt","r");

    int i = 0;
    int j = 0;
    int read = 0;
    char *line = NULL;
    size_t len = 0;

    while ((read = getline(&line, &len, fp)) != -1) {
        i++;
        j += read;
    }

    free(line);    
    fclose(fp);
    printf("The Number Of Lines In That File: %d\n", i);
    printf("The Number Of Chars In That File: %d\n", j);
}
sergej
  • 17,147
  • 6
  • 52
  • 89