Skip site navigation (1)Skip section navigation (2)

FreeBSD Manual Pages

  
 
  

home | help
std::filesy...y::file_size(3) C++ Standard Libarystd::filesy...y::file_size(3)

NAME
       std::filesystem::directory_entry::file_size  -  std::filesystem::direc-
       tory_entry::file_size

Synopsis
	  std::uintmax_t		  file_size()			const;
       (since C++17)
	  std::uintmax_t file_size( std::error_code& ec	) const	noexcept;

	  If  the  file	 size  is  cached in this directory_entry, returns the
       cached value.
	  Otherwise, returns std::filesystem::file_size(path())	or
	  std::filesystem::file_size(path(), ec), respectively.

Parameters
	  ec - out-parameter for error reporting in the	non-throwing overload

Return value
	  The size of the referred-to filesystem object.

Exceptions
	  The overload that does not take a std::error_code& parameter throws
	  filesystem::filesystem_error	on  underlying	OS  API	 errors,  con-
       structed	with p as the
	  first	 path  argument	 and the OS error code as the error code argu-
       ment. The overload
	  taking a std::error_code& parameter sets it to the OS	API error code
       if an OS	API
	  call fails, and executes ec.clear() if no errors occur. Any overload
       not marked
	  noexcept may throw std::bad_alloc if memory allocation fails.

Example
	  Prints the list of files in a	given directory	alongside  with	 their
       sizes in	human
	  readable form.

       // Run this code

	#include <filesystem>
	#include <iostream>
	#include <cstdint>
	#include <cmath>

	struct HumanReadable {
	    std::uintmax_t size	{};

	    template  <typename	 Os> friend Os&	operator<< (Os&	os, HumanRead-
       able hr)
	    {
		int i{};
		double mantissa	= hr.size;
		for (; mantissa	>= 1024.; ++i) {
		    mantissa /=	1024.;
		}
		mantissa = std::ceil(mantissa *	10.) / 10.;
		os << mantissa << "BKMGTPE"[i];
		return i == 0 ?	os : os	<< "B (" << hr.size << ')';
	    }
	};

	int main(int argc, const char* argv[])
	{
	    const auto dir = argc == 2 ? std::filesystem::path{	argv[1]	}
				       : std::filesystem::current_path();

	    for	(std::filesystem::directory_entry const& entry :
		 std::filesystem::directory_iterator(dir)) {
		if (entry.is_regular_file()) {
		    std::cout << entry.path().filename() << " size: "
			      << HumanReadable{entry.file_size()} << '\n';
		}
	    }
	}

Possible output:
	"boost_1_73_0.tar.bz2" size: 104.2MB (109247910)
	"CppCon	2018 - Jon Kalb	Copy Elision.mp4" size:	15.7MB (16411990)
	"cppreference-doc-20190607.tar.xz" size: 6.3MB (6531336)
	"hana.hpp" size: 6.7KB (6807)

See also
	  file_size returns the	size of	a file
	  (C++17)   (function)

http://cppreference.com		  2022.07.31	 std::filesy...y::file_size(3)

Want to link to this manual page? Use this URL:
<https://man.freebsd.org/cgi/man.cgi?query=std::filesystem::directory_entry::file_size&sektion=3&manpath=FreeBSD+Ports+15.0>

home | help