4

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.

richardaum
  • 6,651
  • 12
  • 48
  • 64

2 Answers2

8

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.

Evan Benn
  • 1,571
  • 2
  • 14
  • 20
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • "Anything beyond that in your buffer will not be modified." I think this should be "Anything beyond that in your buffer will be invalid/indeterminate" – Evan Benn Sep 05 '18 at 04:30
  • @Evan Benn what you said is not always true - the reads are done in a loop, if more than one record is read, the data at the end of the buffer is known. – Steve Townsend Sep 05 '18 at 12:47
  • `If a partial member is read, its value is indeterminate.` - While not clear, to me this seems like the implementation is free to munge data one member past the valid members it returns. – Evan Benn Sep 06 '18 at 00:25
  • I confirmed that on my box the array data is munged past the 'valid' read items. – Evan Benn Sep 06 '18 at 01:34
1

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.

dwalter
  • 7,258
  • 1
  • 32
  • 34