fseek() giving 2 different counts when I expected the same count

77 Views Asked by At

If I use

fseek(file_ptr, 0, SEEK_END);
size = ftell(file_ptr);

I get 480000 which is right as I have 60000 x double float at 8 bytes per double in the file.

But when I use

fseek(file_ptr, sizeof(double), SEEK_END);
size = ftell(file_ptr); 

I get 480008 an extra 8 bytes. Anyone know what they are?

2

There are 2 best solutions below

0
Harith On BEST ANSWER

But when I use

fseek(file_ptr, sizeof(double), SEEK_END);
size = ftell(file_ptr); 

I get 480008 an extra 8 bytes

That is because the size of a double on your system is 8 bytes, and fseek() set the file position indicator 8 bytes from SEEK_END.

The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence.


Re:

Anyone know what they are?

This is what the open group's manual page has to say about it:

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

The behavior of fseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.

Note that this behaviour is only specified for POSIX-compliant systems.

0
Roberto Caboni On

The answer is in fseek() man page (Linux OS).

The function prototype is

int fseek(FILE *stream, long offset, int whence);

where offset parameter is described as follows

The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence.

Since your offset is 8 (sizeof double, in your system) and the original file size is 480000, that's why you get 480008.

The manual never mention any limitation preventing the pointer to be set after SEEK_END.