C - 如果缓冲区更大,如何处理文件的最后部分?

时间:2013-02-07 03:44:24

标签: c file io

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

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

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

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

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

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

2 个答案:

答案 0 :(得分:4)

是的,请转动你的参数。

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

size

答案 1 :(得分: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.