I am making a program that reads disk images in C. I am trying to make something portable, so I do not want to use too many OS-specific libraries. I am aware there are many disk images that are very large files but I am unsure how to support these files.
I have read up on fseek
and it seems to use a long int
which is not guaranteed to support values over 231-1. fsetpos
seems to support a larger value with fpos_t
but an absolute position cannot be specified. I have also though about using several relative seeks with fseek
but am unsure if this is portable.
How can I support portably support large files in C?
There is no portable way.
On Linux there are fseeko()
and ftello()
, pair (need some defines, check ftello()
).
On Windows, I believe you have to use _fseeki64()
and _ftelli64()
#ifdef
is your friend
pread()
works on any POSIX-compliant platform (OS X, Linux, BSD, etc.). It's missing on Windows but there are lots of standard things that Windows gets wrong; this won't be the only thing in your codebase that needs a Windows special case.
You can't do it with standard C. Even with relative seeks it's not possible on some architectures.
One approach would be to check the platform at compile time. You can just check the value of LONG_MAX and throw a compile error if it's not large enough. But even that doesn't guarantees that the underlying filesystem supports files larger than 2 or 4GB.
A better way is to use the pre-processor macros supplied by your compiler to check the operating system that your code is being compiled for and write operating system specific specific. The operating system should provide a way to check that the filesystem actually supports files larger than 2GB or 4GB.
来源:https://stackoverflow.com/questions/30657968/can-i-seek-a-position-beyond-2gb-in-c-using-the-standard-library