Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a file's size in C? [duplicate]

Tags:

c

file

size

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.

like image 973
Nino Avatar asked Oct 26 '08 20:10

Nino


People also ask

How can I get a file's size in C?

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.

How do I read file size?

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.

Which function is used to get the size of a file?

The filesize() function returns the size of a file.

How do I check the size of a file in Linux?

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.


2 Answers

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); 
like image 199
Rob Walker Avatar answered Oct 12 '22 02:10

Rob Walker


Using standard library:

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 

Linux/POSIX:

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; 

Win32:

You can use GetFileSize or GetFileSizeEx.

like image 44
Greg Hewgill Avatar answered Oct 12 '22 03:10

Greg Hewgill