How can I figure out the size of a file, in bytes?
#include <stdio.h> unsigned int fsize(char* file){ //what goes here? }
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
On Unix-like systems, you can use POSIX system calls:
staton a path, orfstaton an already-open file descriptor (POSIX man page, Linux man page).(Get a file descriptor from
open(2), orfileno(FILE*)on a stdio stream).Based on NilObject’s code:
Changes:
const char.struct statdefinition, which was missing the variable name.-1on error instead of0, which would be ambiguous for an empty file.off_tis a signed type so this is possible.If you want
fsize()to print a message on error, you can use this:On 32-bit systems you should compile this with the option
-D_FILE_OFFSET_BITS=64, otherwiseoff_twill only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.