2013Asker
2013Asker

Reputation: 2068

C - What's The Fastest Way To Get File Size?

After you have opened a file using:

const char *fMode = "r";
FILE *filePointer = fopen(location,fMode);

What's the fastest cross platform (Windows and Linux) way to get its size so you can allocate the right amount of memory using malloc?

I've seen that ftell only works if you open the file in binary mode.

Upvotes: 0

Views: 2243

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129514

I would recommend using ftell.

It's not 100% accurate, but it's good enough. Unless you are dealing with files that have only one or two characters per line, and LOTS of lines, the overhead is probably not important (sure, if the file has a million lines, AND the platform is Windows or something else where newline is more than one character, then there will be 1M extra bytes allocated. But if each line is, on average, 50 bytes long, you'll be allocating 50MB, so it's a 2% overhead).

The only alternative to ftell is to read every line in the file, and counting the number of characters. And if you want to read the file into memory, that's a pretty poor way to do it.

Suggestion of stat or fstat, or other similar functions will have exactly the same flaw of giving "the number of bytes the file takes up on disk, not the number of characters you'd read" [assuming, again, newlines are more than one character, which is the case on Windows and a few other OS's].

Upvotes: 1

rici
rici

Reputation: 241911

There's really no way to tell exactly how much space a file will occupy in memory if you read the file in non-binary mode on a platform (like Windows) in which the end-of-line characters is more than one byte long.

Nonetheless, unless the file has lots of really short lines, the filesize returned by ftell or fstat will only be a little bit too big.

Upvotes: 0

unxnut
unxnut

Reputation: 8839

You can find the size using stat or fstat before you open the file.

Upvotes: 4

Related Questions