REALFREE
REALFREE

Reputation: 4396

C - How to handle last part of file if buffer is bigger?

isn't it possible to read bytes left in a file that is smaller than buffer size?

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

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

Let's assume size is 4 and file size is 17 bytes. I thought fread can handle last operation as well even if bytes left in file is smaller than buffer size, but apparently it just terminates while loop without reading one last byte.

I tried to use lower system call read() but I couldn't read any byte for some reason.

What should I do if fread cannot handle last part of bytes that is smaller than buffer size?

Upvotes: 4

Views: 2738

Answers (2)

aashoo
aashoo

Reputation: 404

try using "man fread"

it clearly mention following things which itself answers your question:

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.

Upvotes: 0

paddy
paddy

Reputation: 63451

Yep, turn your parameters around.

Instead of requesting one block of size bytes, you should request size blocks of 1 bytes. Then the function will return how many blocks (bytes) it was able to read:

int nread;
while( 0 < (nread = fread(buffer, 1, size, fp)) ) ...

Upvotes: 5

Related Questions