Reading txt file for memory

Asked

Viewed 50 times

1

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

  • Username: User X
  • Sex of user: Male or female
  • User age: X age

The code I have at the moment is as follows::

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’s a bug I’ve been trying to figure out but to no avail. After printing the user’s name and gender in the output, the user prints the age but enters the loop from where it no longer exits. I tried using EOF. I have tried including with '\0' but I can’t figure out how to stop the script if there’s nothing left to read from the file. Any suggestions?

inserir a descrição da imagem aqui

  • I suggest you put an example file with the information you have written, so that the problem is clearer.

  • The text file is set to show the image. I hope it helps.

1 answer

0


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

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 to use the fgetc() function to check the EOF

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

http://www.cplusplus.com/reference/cstdio/feof/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.