[C++] バイト単位のファイルサイズを単位文字付きで表示する

バイト単位のサイズをログファイルや標準出力に出力する場合に分かりやすいように適切な単位(MB,GBなど)で表示するためのサンプルコードです。

[cpp title=”GetFormattedNumber.cpp”]
#include <iostream>

struct SizeUnit {

size_t factor;
std::string unitStr;
};

const static SizeUnit NONE = { 1, "bytes" };
const static SizeUnit KILO = { 1024, "KB" };
const static SizeUnit MEGA = { KILO.factor * 1024, "MB" };
const static SizeUnit GIGA = { MEGA.factor * 1024, "GB" };
const static SizeUnit TERA = { GIGA.factor * 1024, "TB" };

const static int BUFSIZE = 100;

std::string format(const size_t sz, SizeUnit sizeUnit) {

char buf[BUFSIZE];
std::string fmt = sz % sizeUnit.factor == 0 ? "%.0f %s" : "%.1f %s";

std::snprintf(
buf, BUFSIZE, fmt.data(),
static_cast<double>(sz)/static_cast<double>(sizeUnit.factor),
sizeUnit.unitStr.data());

return std::string(buf);
}

std::string getFormattedNumber(const size_t sz){

if( sz > TERA.factor) {
return format(sz, TERA);
} else if( sz > GIGA.factor) {
return format(sz, GIGA);
} else if (sz > MEGA.factor) {
return format(sz, MEGA);
} else if (sz > KILO.factor) {
return format(sz, KILO);
} else {
return format(sz, NONE);
}
}

int main() {

std::cout
<< getFormattedNumber(234) << std::endl
<< getFormattedNumber(34543) << std::endl
<< getFormattedNumber(345387320) << std::endl
<< getFormattedNumber(275123793035) << std::endl
<< getFormattedNumber(31038852073273) << std::endl;
}

[/cpp]

出力結果はこちら

$ ./GetformattedNumber
234 bytes
33.7 GB
329.4 MB
256.2 GB
28.2 TB

kaizawa

闘う兼業主夫プログラマー。外資系IT企業所属。C++、Java、Solaris、Oracle、セキュリティ、DLP(Data Loss Prevention)、D&D、空手二段(極真会館)、柔道初段、柔術白帯ストライプ3(トライフォース)。English/中文

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です