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

时间:2016-10-18 06:05:31

标签: c glibc

根据fwrite

的手册页
  

fread()fwrite()返回成功读取或写入的项目数(即不是数字   的人物)。如果发生错误或达到文件结尾,则返回值为short   项目数(或零)。

我想知道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,即使它确实在文件中写了一些字节。

1 个答案:

答案 0 :(得分:3)

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

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

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

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

获取确切的字节数;现在你从假设的短篇小说中得到512分。