Matthias Kaeppler wrote:
Hello,
in my application, I want to print file sizes in a human readable
format. However, I remember a thread here which dealt with a similar
issue, and people said it'd be a bad idea to write numbers like 1024 and
so on explicitly. Unfortunately I can't remember the reason.
Can you elaborate on that?
Thanks.
Maybe it's a better idea after all if I post my code, and you tell me
whether it's okay or not. The function is supposed to create a string
from an integer holding the formatted size:
Glib::ustring FileBrowser::get_file_size( const boostfs::path& path )
{
Glib::ustring str_size;
try
{
if( boostfs::is_directory(path) )
return "0";
boost::intmax_t size = boostfs::file_size( path );
const int KILO_BYTE = 1024;
const int MEGA_BYTE = KILO_BYTE * 1024;
const int GIGA_BYTE = MEGA_BYTE * 1024;
if( size >= GIGA_BYTE )
{
size /= GIGA_BYTE;
str_size = boost::lexical_cast<Glib::ustring>(size) + " GB";
}
else if( size >= MEGA_BYTE )
{
size /= MEGA_BYTE;
str_size = boost::lexical_cast<Glib::ustring>(size) + " MB";
}
else if( size >= KILO_BYTE )
{
size /= KILO_BYTE;
str_size = boost::lexical_cast<Glib::ustring>(size) + " KB";
}
else
{
str_size = boost::lexical_cast<Glib::ustring>(size) + " B";
}
}
catch( const boostfs::filesystem_error& e )
{
std::cerr << e.what() << std::endl;
}
return str_size;
}
By the way, it would be cool if the file size wasn't reduced to a
rounded integer, but a float or double has too many digits.
Any idea how I can trim them to only one digit behind the dot, e.g.:
12.3 MB instead of 12.3xxxxxxx MB or such.
--
Matthias Kaeppler