2

This question is in reference to How can I get a file's size in C?

Most answers suggesting the use of the function stat to get the file length also comes with a tag to do error checking.

What kind of error checking do we need here?

Thanks.

Community
  • 1
  • 1
Lipika Deka
  • 3,774
  • 6
  • 43
  • 56

2 Answers2

3

Like many Unix/POSIX API functions, stat(2) returns a negative integer on failure. Unfortunately, this integer is always -1 for stat. Hence, you need to check the errno global variable (defined in <errno.h>) to see what the exact error was.

Ben has listed some of the errors you can run into; the errno codes for these and other errors are listed in the stat manpage.

Community
  • 1
  • 1
Michael Ratanapintha
  • 39,422
  • 4
  • 33
  • 40
  • 1
    Please avoid giving pagerank to linux.die.net. It has very outdated manpages and is completely unmaintained. The copies on kernel.org are authoritative for Linux. – R.. GitHub STOP HELPING ICE Jul 03 '11 at 05:50
  • R..: All right! I'll fix it! Geez, it's not such a tragedy (unless there are specific errors in the stat(2) and errno(3) manpages that need fixing). I'd just like a webified manual page that doesn't look like someone just wrapped the output of `nroff -man` in a pre tag... – Michael Ratanapintha Jul 03 '11 at 07:39
  • No need to get upset. I didn't -1 or anything, I just suggested changing it and even said "please". :-) – R.. GitHub STOP HELPING ICE Jul 03 '11 at 14:58
2
  • The file might not exist
  • You might not have permission to access its metadata
  • A network mount point might be unreachable, or there could be some other read error
  • It might be a special file (device node, for example, or fifo) that doesn't have a size
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720