Skip to content

Commit 71f3ddd

Browse files
committed
added routine that builds a file size string from a number of bytes
1 parent 425cf44 commit 71f3ddd

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Flux/flxUtils.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,4 +397,32 @@ void flx_utils::timestampISO8601( time_t &t_time, char * buffer, size_t length,
397397
snprintf(szTmp, sizeof(szTmp), "%c%02d:%02d", chSign, tz_hrs, tz_min);
398398

399399
strlcat(buffer, szTmp, length);
400+
}
401+
402+
//---------------------------------------------------------------------------------------------------
403+
// formatBytes()
404+
//
405+
// Return a formatted byte string. This returns values of B (1000), not iB (1024)
406+
407+
void flx_utils::formatByteString(uint64_t nBytes, uint prec, char *szBuffer, size_t len)
408+
{
409+
410+
char *sizeNames[] = {"Bytes", "KB", "MB", "GB", "TB"};
411+
412+
if (nBytes < 0)
413+
nBytes = 0;
414+
415+
if (prec < 0)
416+
prec = 0;
417+
418+
double tmp1 = floor( (nBytes ? log(nBytes) : 0) / log(1000.));
419+
420+
// overflow our name array?
421+
if ( tmp1 > (sizeof(sizeNames)/sizeof(char*))-1)
422+
tmp1 = (sizeof(sizeNames)/sizeof(char*))-1;
423+
424+
char szFormat[32];
425+
snprintf(szFormat, sizeof(szFormat), "%%.%df%%s", prec);
426+
snprintf(szBuffer, len, szFormat, nBytes/pow(1000., tmp1), sizeNames[(int)tmp1]);
427+
400428
}

src/Flux/flxUtils.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ void uptime(uint32_t &days, uint32_t &hours, uint32_t &minutes, uint32_t &secs,
5959

6060
void timestampISO8601(time_t &theTime, char * buffer, size_t length, bool bTZ=false);
6161

62+
void formatByteString(uint64_t nBytes, uint prec, char *szBuffer, size_t len);
6263
} // namespace flx_utils
6364

6465
/*

0 commit comments

Comments
 (0)