Problem with reading a file

Hello, here's my problem. When I read a text file, and it reaches the last line, even though I use the eof() function, it keeps reading and printing. Can you help me please? Here's the code. Thanks in advance.

#include
#include
#include

void main(void)
{
FILE *f;
char linea[100];
f=fopen("somefile.txt","r");
if(f!=NULL)
{
do{
fgets(linea,100,f);
if(feof(f)!=EOF)
{
printf("%s",linea);
}
}while(feof(f)!=EOF);
fclose(f);
printf("
Ready
");
}
else
printf("
Couldn't read file
",archivo2);
}

Comments

  • : Hello, here's my problem. When I read a text file, and it reaches the last line, even though I use the eof() function, it keeps reading and printing. Can you help me please? Here's the code. Thanks in advance.
    :
    : #include
    : #include
    : #include
    :
    : void main(void)
    : {
    : FILE *f;
    : char linea[100];
    : f=fopen("somefile.txt","r");
    : if(f!=NULL)
    : {
    : do{
    : fgets(linea,100,f);
    : if(feof(f)!=EOF)
    : {
    : printf("%s",linea);
    : }
    : }while(feof(f)!=EOF);
    : fclose(f);
    : printf("
    Ready
    ");
    : }
    : else
    : printf("
    Couldn't read file
    ",archivo2);
    : }
    :
    [purple][code]
    int feof(FILE *stream);

    The function returns a nonzero value if the end-of-file indicator is set
    for the stream [italic]stream[/italic]. Otherwise, it returns 0.[/code]
    so, the condition of checking whether or not the EOF has reached shud be

    [b][black]do {
    /*...*/
    } while(feof(f)==0);[/b][/black]

    and there is no need of another if checking inside the loop.
    [/purple]
    [hr][purple]~Donotalo()[/purple]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion