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.
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.
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.
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.
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.
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();
You can use stat system call:
#ifdef WIN32
_stat64()
#else
stat64()
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