Reading txt file to memory

1

I am trying to read the file that contains only 3 elements.

  • User name: User X
  • User Sex: Male or female
  • User age: X age

The code I have at the moment is the following:

FILE* fp;
char linha[500];

fp = fopen("Ficheiro Teste.txt","r");

if(fp == NULL)
{
    printf("Empty Text File!\n");
}
else
{
    while(fp != EOF)
    {
        fgets(linha,sizeof(linha),fp);
        printf("%s",linha);
    }
    //fclose(fp);
}
fclose(fp);

The code apparently works but there is a bug that I have tried to figure out but to no avail. After printing the output of the user's name and the gender of the user, it also prints the age but enters the loop from where it does not exit any more. I tried using EOF. I have tried even with '%code%' but I can not figure out how to stop the program if there is nothing left to read from the file. Any suggestions?

    
asked by anonymous 30.01.2018 / 14:51

1 answer

0

Use the feof () function; To determine a break in the loop; The function checks when the end of the file is

FILE* fp;
char linha[500];

fp = fopen("Ficheiro Teste.txt","r");

if(fp == NULL)
{
    printf("Empty Text File!\n");
}
else
{
    while(1)
    {
        fgets(linha,sizeof(linha),fp);
        printf("%s",linha);

      if(feof(fp))
           break;

    }

}
fclose(fp);

Another way is for you to use the fgetc () function to check the EOF

 while(fgetc(fp) != EOF)
    {
        fgets(linha,sizeof(linha),fp);
        printf("%s",linha);
    }

link

    
30.01.2018 / 15:28