如何(合规地)从 tmpfile() 读取?

huangapple go评论71阅读模式
英文:

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

问题

以下是翻译好的部分:

有关“如何获取tmpfile()创建的路径”的问题已经存在,但我理解标准并不保证创建的文件具有可访问的路径。因此,如果标准不保证这一点,那么在写入文件后从tmpfile中读取的“标准”方式是什么呢?(当然,如果永远不写入tmpfile,或者永远不读取它,那么tmpfile就没有意义)

我目前有这段代码:

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));

这段代码输出如下:

err: 1/0
err: 0/1

我在onlinegdb.com上运行这段代码,因为我在这台机器上没有编译器,所以可能是onlinegdb不符合标准,但我想知道是这个原因还是我在代码中做错了什么。

英文:

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.

答案1

得分: 1

> 如何(合规地)从tmpfile()读取?

通常像从任何其他FILE*一样,使用fread

您的代码是正确的。它从文件中读取。在文件的末尾没有要读取的内容,因此fread返回0,并设置了feof

如果您希望在使用fwrite写入文件后从开头读取文件,请先使用fseek

英文:

> 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.

huangapple
  • 本文由 发表于 2023年8月5日 01:03:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定