Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file size in bytes with C++17

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.

Methods from other (old QA's) on .sx

  • stat.h (wrapper sprintstatf), uses syscall

  • tellg(), returns per definition a position but not necessarily bytes. The return type is not int.

like image 463
Jonas Stein Avatar asked Jun 30 '19 20:06

Jonas Stein


People also ask

How to get file size in bytes in c?

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.

How do you find the file size?

Click the file or folder. Press Command + I on your keyboard. A window opens and shows the size of the file or folder.

How do I get the size of a text file in C++?

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.


Video Answer


1 Answers

<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

like image 103
HolyBlackCat Avatar answered Sep 21 '22 06:09

HolyBlackCat