gpt4 book ai didi

c - 为什么我不能 "freopen" "tmpfile"?

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:24 26 4
gpt4 key购买 nike

我尝试编译并运行具有以下几行的 C 代码:

FILE *preproc_producer = NULL;
preproc_producer = tmpfile();
// preproc_producer is not NULL here
preproc_producer = freopen(NULL, "r+", preproc_producer);
// preproc_producer is NULL here

但是,运行代码时,preproc_producerNULL 结尾,错误代码为Stale NFS file handle

  1. 上面的代码有什么问题?

  2. 这里调用freopen 的目的是什么?我注释掉了 freopen 行,程序的其余部分似乎可以正常工作。

我正在使用 GCC 4.7.2,在 Docker 0.6.7 Linux 容器中运行 Ubuntu 64 12.04。上面的代码似乎在 Docker 容器之外工作。

更新: strace 转储:

stat("/tmp", {st_mode=S_IFDIR|S_ISVTX|0777, st_size=4096, ...}) = 0
gettimeofday({1385247432, 199732}, NULL) = 0
getpid() = 127
open("/tmp/tmpf9l14HD", O_RDWR|O_CREAT|O_EXCL, 0600) = 3
unlink("/tmp/tmpf9l14HD") = 0
fcntl(3, F_GETFL) = 0x8002 (flags O_RDWR|O_LARGEFILE)
brk(0) = 0xc94000
brk(0xcb5000) = 0xcb5000
fstat(3, {st_mode=S_IFREG|0600, st_size=0, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f7afb9d0000
lseek(3, 0, SEEK_CUR) = 0
lstat("/proc/self/fd/3", {st_mode=S_IFLNK|0700, st_size=64, ...}) = 0
munmap(0x7f7afb9d0000, 4096) = 0
open("/proc/self/fd/3", O_RDWR) = -1 ESTALE (Stale NFS file handle)

最佳答案

来自 C99 标准:

The freopen function opens the file whose name is the string pointed to by filenameand associates the stream pointed to by stream with it. The mode argument is used justas in the fopen function.

If filename is a null pointer, the freopen function attempts to change the mode ofthe stream to that specified by mode, as if the name of the file currently associated withthe stream had been used. It is implementation-defined which changes of mode arepermitted (if any), and under what circumstances.

所以,可能是谁写了这段代码,打算将临时文件打开模式从 w+b 更改为 r+ (主要归结为将流更改为文本模式).不幸的是,在您的实现中似乎无法以这种方式更改临时文件的打开模式。

我想这可能是因为关闭临时文件也会删除它,但也可能是 freopenglibc 实现不支持模式freopen 的更改(联机帮助页甚至没有提到将 NULL 作为第一个参数传递的可能性)。

关于c - 为什么我不能 "freopen" "tmpfile"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20168275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com