How to get file size in ANSI C without fseek and ftell?

math4tots picture math4tots · Mar 22, 2012 · Viewed 11.1k times · Source

While looking for ways to find the size of a file given a FILE*, I came across this article advising against it. Instead, it seems to encourage using file descriptors and fstat.

However I was under the impression that fstat, open and file descriptors in general are not as portable (After a bit of searching, I've found something to this effect).

Is there a way to get the size of a file in ANSI C while keeping in line with the warnings in the article?

Answer

Carl Norum picture Carl Norum · Mar 22, 2012

In standard C, the fseek/ftell dance is pretty much the only game in town. Anything else you'd do depends at least in some way on the specific environment your program runs in. Unfortunately said dance also has its problems as described in the articles you've linked.

I guess you could always read everything out of the file until EOF and keep track along the way - with fread() for example.