Pregunta

I try to read a file to which my FILE* fp points and I want to know where the end of the file is. Therefore I use fseek(); At the end of the file, I want to write data from my structure data.

void printData(FILE *fp)
{
    struct data tmp;
    fseek(fp,0,SEEK_END);
    while(fread(&tmp,sizeof(struct data),1,fp) > 0)
    {
        puts("test2");
        printf("Vorname: %s\n",tmp.vorname);
        printf("Nachname: %s\n",tmp.name);
        printf("Adresse: %s\n",tmp.adresse);

    }
}

This is how my structure is defined:

struct data
{
    char name[30];
    char vorname[20];
    char adresse[50];
};

My Problem is, that the while loop isn't executed even once. Do I forgot something?

¿Fue útil?

Solución

fseek(fp,0,SEEK_END) positions the file pointer at the end of the file (starting point end of the file offset 0), when you then try to read from the file fread of course doesn't read anything.

instead open the file in append mode and fwrite the number of records, these will be appended to the file.

Otros consejos

The third variable '1' in fread actually indicates number of items to be read and you are just reading one item. Refer fread document for this: http://pubs.opengroup.org/onlinepubs/009696899/functions/fread.html

After seeking to the end-of-file you won't be able to read anything. If you just want to know the file size, you can mybe use fstat() instead, or you do the fseek() after reading what you wanted to read, thad depends on what you're trying to achieve.

fread() is used for reading contents from file not for writing.

Use fwrite() for writing contents to file.

Like:

fwrite(&tmp , 1 , sizeof(struct data) , fp );

Read more about: fread() and fwrite()

You are seeking to the start of the file, since you're setting the offset to 0. That doesn't sound like what you want to be doing, but on the other hand seeking to the end and then trying to read would also fail. I'm confused. :/

Could it be that you meant fwrite(), rather than `fread()? Not likely since the rest of the code prints the results after the I/O, which is logical for reading but not for writing.

It would be helpful with more information, like your file is opened and what it does contain when you run the program.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top