4

バッファサイズよりも小さいファイルに残っているバイトを読み取ることはできませんか?

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

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

サイズが 4 で、ファイル サイズが 17 バイトであるとします。ファイルに残っているバイトがバッファサイズよりも小さい場合でも、 fread は最後の操作も処理できると思いましたが、最後のバイトを読み取らずにwhileループを終了するようです。

下位システムコール read() を使おうとしたのですが、なぜか1バイトも読み込めませんでした。

fread がバッファーサイズよりも小さいバイトの最後の部分を処理できない場合はどうすればよいですか?

4

2 に答える 2

5

はい、パラメータを変えてください。

size1 ブロックのバイトを要求する代わりにsize、1 バイトのブロックを要求する必要があります。次に、関数は読み取ることができたブロック (バイト) の数を返します。

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

「マンフレッド」を使ってみてください

それ自体があなたの質問に答える次のことを明確に述べています:

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 に答える