gpt4 book ai didi

c - fwrite 是否可以写入一些字节但返回零?

转载 作者:行者123 更新时间:2023-12-02 04:53:34 27 4
gpt4 key购买 nike

根据fwrite的手册页:

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

我想知道 fwrite(ptr, 65537, 1, fp) 是否可以仅写入 512 字节并返回零?

我尝试快速跟踪 glibc-2.12.2 源代码。

malloc/malloc.c:#define fwrite(buf, size, count, fp) _IO_fwrite (buf, size, count, fp) 

我猜真正的实现是在 iofwrite.c 中。

_IO_size_t
_IO_fwrite (buf, size, count, fp)
const void *buf;
_IO_size_t size;
_IO_size_t count;
_IO_FILE *fp;
{
_IO_size_t request = size * count;
_IO_size_t written = 0;
CHECK_FILE (fp, 0);
if (request == 0)
return 0;
_IO_acquire_lock (fp);
if (_IO_vtable_offset (fp) != 0 || _IO_fwide (fp, -1) == -1)
written = _IO_sputn (fp, (const char *) buf, request);
_IO_release_lock (fp);
/* We have written all of the input in case the return value indicates
this or EOF is returned. The latter is a special case where we
simply did not manage to flush the buffer. But the data is in the
buffer and therefore written as far as fwrite is concerned. */
if (written == request || written == EOF)
return count;
else
return written / size;
}

所以,我猜即使 fwrite 确实已经向文件写入了一些字节,它的返回码也可能返回 0。

最佳答案

是的 - fwrite(ptr, 65537, 1, fp) 可能会返回 0 作为返回码,即使它确实向文件中写入了一些字节。

例如,如果磁盘上只剩下 512 字节的空间,那么您的写入很短,但它写入了 0 个完整的 65537 字节单位(这是一个奇怪的数字;通常会是 65536,不会吗?),所以返回值一定是0。

如果你想知道实际写了多少,你应该使用:

 nbytes = fwrite(ptr, 1, 65537, fp);

获取准确的字节数;现在您将从假设的简短写入中得到 512。

关于c - fwrite 是否可以写入一些字节但返回零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100701/

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