How can I find out the size of a file I opened with an application written in C ? I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using malloc()
. Just writing malloc(10000*sizeof(char));
is IMHO a bad idea.
The idea is to use fseek() in C and ftell in C. Using fseek(), we move file pointer to end, then using ftell(), we find its position which is actually size in bytes.
Locate the file or folder whose size you would like to view. Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
The filesize() function returns the size of a file.
The best Linux command to check file size is using du command. What we need is to open the terminal and type du -sh file name in the prompt. The file size will be listed on the first column. The size will be displayed in Human Readable Format.
You need to seek to the end of the file and then ask for the position:
fseek(fp, 0L, SEEK_END); sz = ftell(fp);
You can then seek back, e.g.:
fseek(fp, 0L, SEEK_SET);
or (if seeking to go to the beginning)
rewind(fp);
Assuming that your implementation meaningfully supports SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of file size = ftell(f); // get current file pointer fseek(f, 0, SEEK_SET); // seek back to beginning of file // proceed with allocating memory and reading the file
You can use stat
(if you know the filename), or fstat
(if you have the file descriptor).
Here is an example for stat:
#include <sys/stat.h> struct stat st; stat(filename, &st); size = st.st_size;
You can use GetFileSize or GetFileSizeEx.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With