4

是否可以读取小于缓冲区大小的文件中剩余的字节?

char * buffer = (char *)malloc(size);
FILE * fp = fopen(filename, "rb");

while(fread(buffer, size, 1, fp)){
     // do something
}

假设大小为 4,文件大小为 17 字节。我认为 fread 也可以处理最后一个操作,即使文件中剩余的字节小于缓冲区大小,但显然它只是终止 while 循环而不读取最后一个字节。

我尝试使用较低的系统调用 read() 但由于某种原因我无法读取任何字节。

如果 fread 无法处理小于缓冲区大小的最后一部分字节,我该怎么办?

4

2 回答 2

5

是的,把你的参数调过来。

size您应该请求1 个字节的块,而不是请求一个字节size块。然后该函数将返回它能够读取多少块(字节):

int nread;
while( 0 < (nread = fread(buffer, 1, size, fp)) ) ...
于 2013-02-07T03:47:59.913 回答
0

尝试使用“man fread”

它清楚地提到了以下本身回答您的问题的事情:

SYNOPSIS
size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);

DESCRIPTION
  fread() copies, into an array pointed to by ptr, up to nitems items of
  data from the named input stream, where an item of data is a sequence
  of bytes (not necessarily terminated by a null byte) of length size.
  fread() stops appending bytes if an end-of-file or error condition is
  encountered while reading stream, or if nitems items have been read.
  fread() leaves the file pointer in stream, if defined, pointing to the
  byte following the last byte read if there is one.

  The argument size is typically sizeof(*ptr) where the pseudo-function
  sizeof specifies the length of an item pointed to by ptr.

RETURN VALUE
  fread(), return the number of items read.If size or nitems is 0, no
  characters are read or written and 0 is returned.

  The value returned will be less than nitems only if a read error or
  end-of-file is encountered.  The ferror() or feof() functions must be
  used to distinguish between an error condition and an end-of-file
  condition.
于 2013-02-07T04:10:35.847 回答