cfileunixdirent.h

How to get file size without holes in C


So I was trying to get the size of a file in C.

I am aware of 2 ways of getting a file size in C, to use the st_size member of the stat structure or use fseek between the beginning and end of the file.

However, I was concerned with whether the st_size method would report the "false size" of a file if it has holes. I'd imagine the fseek method would definitely produce the incorrect result if the file has holes, correct?

According to the book "Advanced Programming in the UNIX Environment", section 4.12, one way of getting around this is to copy the file into memory and reading its size from memory. But I couldn't figure out how to do this in C so I was wondering how exactly you could do that.

Any help is appreciated.


Solution

  • Assuming you mean "holes" between physical blocks on disk where the file's data is stored - those don't count as part of the file, and both methods will only regard proper file data. In the file abstraction, there are no "holes".