Funcion feof(pf)
¿Alguien me podria decir xq este algoritmo me lee dos veces el ultimo caracter del fichero creado?¿Me podrian dar una solucion para que solo me lo leyera una vez?
#include <stdio.h>
void main(void)
{
FILE *pf;int i;char a;
pf=fopen("c:\maestro.txt","w");
for(i=0;i<4;i++)
{scanf("%c",&a);flushall();
fwrite(&a,sizeof(char),1,pf);
}
fclose(pf);
pf=fopen("c:\maestro.txt","r");
while(feof(pf)==0)
{
fread(&a,sizeof(char),1,pf);
printf("%c",a);
}
}
Contestenme lo antes posible. Gracias.
#include <stdio.h>
void main(void)
{
FILE *pf;int i;char a;
pf=fopen("c:\maestro.txt","w");
for(i=0;i<4;i++)
{scanf("%c",&a);flushall();
fwrite(&a,sizeof(char),1,pf);
}
fclose(pf);
pf=fopen("c:\maestro.txt","r");
while(feof(pf)==0)
{
fread(&a,sizeof(char),1,pf);
printf("%c",a);
}
}
Contestenme lo antes posible. Gracias.
te envio el programa arreglado :
#include <stdio.h>
void main(void)
{
FILE *pf;
int i;
char a;
pf = fopen("c:\maestro.txt","w");
for(i=0;i<4;i++)
{
scanf("%c",&a);flushall();
fwrite(&a,sizeof(char),1,pf);
}
fclose(pf);
pf = fopen("c:\maestro.txt","r");
fread(&a,sizeof(char),1,pf);
while(feof(pf)==0)
{
printf("%c",a);
fread(&a,sizeof(char),1,pf);
}
}
La solucion consiste en leer del archivo una vez, antes de entrar al while. Este es un arilugio comun en computacion.
#include <stdio.h>
void main(void)
{
FILE *pf;
int i;
char a;
pf = fopen("c:\maestro.txt","w");
for(i=0;i<4;i++)
{
scanf("%c",&a);flushall();
fwrite(&a,sizeof(char),1,pf);
}
fclose(pf);
pf = fopen("c:\maestro.txt","r");
fread(&a,sizeof(char),1,pf);
while(feof(pf)==0)
{
printf("%c",a);
fread(&a,sizeof(char),1,pf);
}
}
La solucion consiste en leer del archivo una vez, antes de entrar al while. Este es un arilugio comun en computacion.
Como bien dice noel, hay que leer al menos una vez antes del while.
El motivo es que feof() no devuelve true hasta DESPUÉS de leer el fin de fichero. Por ello, el mecanismo correcto es
bucle
leer dato
si es fin de fichero salir
tratar dato
fin de bucle
o bien
leer dato
bucle hasta fin de fichero
tratar dato
leer siguiente dato
fin de bucle
Se bueno.
El motivo es que feof() no devuelve true hasta DESPUÉS de leer el fin de fichero. Por ello, el mecanismo correcto es
bucle
leer dato
si es fin de fichero salir
tratar dato
fin de bucle
o bien
leer dato
bucle hasta fin de fichero
tratar dato
leer siguiente dato
fin de bucle
Se bueno.
