Question

I have a question:

I am using fread to read a file.

typedef struct {
    int ID1;
    int ID2;
    char string[256];
} Reg;

Reg *A = (Reg*) malloc(sizeof(Reg)*size);

size = FILESIZE/sizeof(Reg);

fread (A, sizeof(Reg), size, FILEREAD);

Using a loop, consecutively call this call, to make me read my entire file.

What will happen when I get near the end of the file, and I can not read "size" * sizeof (Reg), or if you are only available to read half this amount, what will happen with my array A. It will be completed? The function will return an error?

Knowing how the file was read by the fread through?

Edi1: Exactly, if the division is not exact, when I read the last bit smaller file size that I'll read things that are not on file, I'm wondering with my vector resize to the amount of bytes that I can read, or develop a dynamic better.

Was it helpful?

Solution

fread returns the number of records it read. Anything beyond that in your buffer may be mangled, do not rely on that data.

fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count.

The function will not read past the end of the file : the most likely occurrence is that you will get a bunch of full buffers and then a (final) partial buffer read, unless the file size is an exact multiple of your buffer length.

Your logic needs to accommodate this - the file size gives you the expected total number of records so it should not be hard to ignore trailing data in the buffer (after the final fread call) that corresponds to uninitialized records. A 'records remaining to read' counter would be one approach.

OTHER TIPS

fread() returns the number of elements it could read. So you have to check the return value of fread() to find out how many elements in your array are valid.

It will return a short item count or zero if either an error occurred or EOF has is reached. You will have to use feof() ond ferror() in this case to check what condition is met.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top