/** NOTE: This function trashes the current position in file **/
/** Does no error checking either **/
long int GetFileSize(FILE* FilePointer) {
fseek(FilePointer, 0L, SEEK_END);
long int ReturnVal = ftell(FilePointer);
fseek(FilePointer, 0L, SEEK_SET);
return ReturnVal;
}
I doubt it. After all, a single system call will give you the file size, and a lot of other information about a file, without trashing the position of the file pointer.
This is not exactly on-topic but I have reimplemented "print decimal numbers" in assembly many times and it is always painful. My latest implementation printed numbers like this:
iansjack wrote:I doubt it. After all, a single system call will give you the file size, and a lot of other information about a file, without trashing the position of the file pointer.
I don't agree that "do this with posix" is a correct answer, because that would actually make the code less portable. The fact that posix ignores the "b" mode means that all files have all the properties of both text and binary files and therefore must support SEEK_END and character-accurate reporting. In addition, "need not support" does mean that fseek-ftell pairs work de-facto on other platforms - most importantly of which is windows, even though it might pose an implementation risk on operating systems you won't practically encounter.
In other words. KISS wins.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
I quite agree. Most platforms provide a single API call to determine file size and this is the one to use (KISS). There is no guaranteed portable way to determine file size.
I'd also comment that resusable code most emphatically should include error checking, preferably wouldn't have side effects, and you would hope it would work with files larger than 2GB .
iansjack wrote:
There is no guaranteed portable way to determine file size.
Unless your fgetc()/fread() returns/sets EOF on a binary file later than the actual end of file is reached and unless it's not a real binary file, there certainly is.
iansjack wrote:Let's face it, if the OS provides an API to obtain the files size it's crazy not to use it.
Are you serious? I heard that writing portable code might be important for projects written in C. If we broke compatibility, it would be reasonable to do it thoroughly. It is quite lame to do it on such a small scale.
I think for me the thing I find the least in existing libraries is having an idmap. A class that maps instances to IDs. You use it for any kind of hard interface where you want to give out handles and validate them when they come back - kernel boundary, remote calls, ... Biggest property is that they are usually small and that they are not reused or moved until freed.