Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way to get file size in C/C++

I need to determin the byte size of a file.

The coding language is C++ and the code should work with Linux, windows and any other operating system. This implies using standard C or C++ functions/classes.

This trivial need has apparently no trivial solution.

like image 975
chmike Avatar asked Mar 11 '10 10:03

chmike


People also ask

How do I get the size of a file 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 check the size of a file in Linux?

Using the ls Command –l – displays a list of files and directories in long format and shows the sizes in bytes. –h – scales file sizes and directory sizes into KB, MB, GB, or TB when the file or directory size is larger than 1024 bytes. –s – displays a list of the files and directories and shows the sizes in blocks.

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

don't worry we have a got a UNIX command to do that for you and command is "df" which displays the size of the file system in UNIX. You can run "df" UNIX command with the current directory or any specified directory.

How do I see the size of a file in bash?

Another method we can use to grab the size of a file in a bash script is the wc command. The wc command returns the number of words, size, and the size of a file in bytes.


2 Answers

Using std's stream you can use:

std::ifstream ifile(....);
ifile.seekg(0, std::ios_base::end);//seek to end
//now get current position as length of file
ifile.tellg();

If you deal with write only file (std::ofstream), then methods are some another:

ofile.seekp(0, std::ios_base::end);
ofile.tellp();
like image 61
Dewfy Avatar answered Sep 20 '22 17:09

Dewfy


You can use stat system call:

#ifdef WIN32 
_stat64()
#else
stat64()
like image 45
Adil Avatar answered Sep 21 '22 17:09

Adil