C - How to handle the last part of the file if the buffer is larger?
Is it not possible to read the bytes left in a file that is smaller than the buffer size?
char * buffer = (char *)malloc(size);
FILE * fp = fopen(filename, "rb");
while(fread(buffer, size, 1, fp)){
// do something
}
Suppose the size is 4 and the file size is 17 bytes. I thought fread could handle the last operation as well, even if the bytes left in the file are less than the buffer size, but it seems to just terminate the while loop without reading the last byte.
I tried using the lower read () system call, but for some reason I couldn't read any byte.
What if fread cannot process the last portion of bytes less than the buffer size?
+3
source to share
2 answers
try using "man fread"
it clearly states the following things which themselves answer 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.
0
source to share