Lipika Deka
Lipika Deka

Reputation: 3894

Error checking when finding file length using stat

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.

Upvotes: 2

Views: 650

Answers (2)

Michael Ratanapintha
Michael Ratanapintha

Reputation: 40627

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.

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283803

  • 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

Upvotes: 2

Related Questions