Search code examples
cstringcharfgets

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


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

Solution

  • 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.