Are there pitfalls for specific operating systems, I should know of?
There are many duplicates (1, 2, 3, 4, 5) of this question but they were answered decades ago. The very high voted answers in many of these questions are wrong today.
stat.h (wrapper sprintstatf), uses syscall
tellg(), returns per definition a position but not necessarily bytes. The return type is not int
.
Using stat() function The stat() function takes the file path and returns a structure containing information about the file pointed by it. To get the size of the file in bytes, use the st_size field of the returned structure.
Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.
Use the std::filesystem::file_size Function to Get File Size in C++ std::filesystem::file_size is the C++ filesystem library function that retrieves the size of the file in bytes.
<filesystem>
(added in C++17) makes this very straightforward.
#include <cstdint> #include <filesystem> // ... std::uintmax_t size = std::filesystem::file_size("c:\\foo\\bar.txt");
As noted in comments, if you're planning to use this function to decide how many bytes to read from the file, keep in mind that...
...unless the file is exclusively opened by you, its size can be changed between the time you ask for it and the time you try to read data from it.
– Nicol Bolas
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