Home > Mobile >  Why fgets just have one line when i want to count the number of char
Why fgets just have one line when i want to count the number of char

Time:05-19

I tried this to count the number of char in a .txt that looks like that

ID2;Orelsan;San;Musiques\\Orelsan San.mp3
ID1;Rick Astley;Never Gonna Give You Up;Musiques\\Rick Astley - Never Gonna Give You Up.mp3

I wrote this but the stringsize is equal to the number of char in line 2

int search(){

FILE *inputFile;
char buffer[255];
int sizestring=0;

inputFile=fopen("bddmp3.txt","rt");

fgets(buffer2,255,inputFile);
while(inputFile!=EOF){
    sizestring  ;
}
printf("%d",sizestring);

I tried another way using strlen, but i have the same problem, i just have the length of the first line

FILE *inputFile;
char buffer[255];
int toto;
int stringsize=0;

inputFile=fopen("bddmp3.txt","r");

stringsize= strlen(fgets(buffer,255,inputFile));
printf("taille :%d\n",stringsize);

CodePudding user response:

fgets returns NULL (and not EOF) if there is no more data left to read.

You probably want this:

inputFile = fopen("bddmp3.txt", "rt");
if (inputFile == NULL) {
  .. handle error
}

while (fgets(buffer2,255,inputFile) != NULL) {
    sizestring  ;
}

This doesn't make sense:

while(inputFile!=EOF){
    sizestring  ;
}
  1. you compare inputFile which is a FILE* to an int which doesn't make any sense
  2. sizestring cannot possibly change inputFile, therefore this loop will most likely run for ever.

CodePudding user response:

A suggestion: Programs like this are better written in terms of fgetc(), which reads single characters. You can then examine each character and easily count lines (by counting '\n' i.e. newlines) or the total number of characters. With this approach, you do not need to allocate a buffer for each line (your current problem would have a bug: what happens if the line is over 255 characters?), and it can easily handle files with lines of any length. Reading character-by-character with fgetc() is not inefficient, because of the buffering implemented in the stdio library.

  • Related