cfreadtemporary-files

How can I (compliantly) read from a tmpfile()?


There are questions already for "how do I get the path created by tmpfile()?" but my understanding is that the standard does not guarantee that the file created has an accessible path. So, if the standard does not guarantee that, then what is the "standard" way to read from a tmpfile after you've written to it? (and of course, there's no point to a tmpfile that never gets written to, and there's no point writing if you never read it back)

I currently have this code:

struct foo {
    ...
};

FILE *fp = tmpfile();
struct foo x = { ... };
struct foo y = { ... };
int err = fwrite(&x, sizeof(struct foo), 1, fp);
printf("err: %x/%x\n", err, errno);
fflush(fp);

err = fread(&y, sizeof(struct foo), 1, fp);
printf("err: %x/%x\n", err, feof(fp));

which gives the output

err: 1/0
err: 0/1

I am running this code on onlinegdb.com because I don't have a compiler on this machine, so it could be that onlinegdb is not in compliance, but I would like to know whether it's that or if I'm doing something wrong in my code.


Solution

  • How can I (compliantly) read from a tmpfile()?

    Normally like from any other FILE*, with fread.

    Your code is correct. It reads from the file. There is nothing to read on the end of the file, so fread returns 0 and feof is set.

    If you want to read a file from the beginning after you have fwrite-tten to it, fseek it first.