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);
}