1 #include <iostream> 2 #include <windows.h> 3 using namespace std; 4
1 /*文件大小格式化 2 *param [in] dwSize xx.xxB 、xx.xxKb 、xx.xxM 3 */ 4 5 LPCTSTR CFileUtil::FileSizeToFormat(DWORD dwSize) 6 { 7 TCHAR* strSize = new TCHAR[20]; 8 ZeroMemory(strSize,sizeof(TCHAR) * 20); 9 10 double i = pow((double)2,10); 11 12 if (dwSize < pow((double)2,10))//dwSize < 1024 13 { 14 _stprintf_s(strSize,20,TEXT("%dB"),dwSize);//文件大小 B 15 } 16 else if (pow((double)2,10) <= dwSize && dwSize< pow((double)2,20))// 1024 <= dwSize < 1024*1024 17 { 18 float fSize = (float)(dwSize*100/1024)/100; 19 _stprintf_s(strSize,20,TEXT("%.2fKB"),fSize); 20 } 21 else if (pow((double)2,20) <= dwSize && dwSize < pow((double)2,30))// 1024*1024 <= dwSize < 1024*1024*1024 22 { 23 float fSize = (float)(dwSize/1024*100/1024)/100; 24 _stprintf_s(strSize,20,TEXT("%.2fM"),fSize);//文件大小 M 25 } 26 else if (pow((double)2,30) <= dwSize && dwSize < pow((double)2,40)) // 1024*1024*1024 <= dwSize < 1024*1024*1024*1024 27 { 28 float fSize = (float)(dwSize/1024*100/1024/1024)/100; 29 _stprintf_s(strSize,20,TEXT("%.2fG"),fSize);//文件大小 G 30 } 31 else 32 { 33 float fSize = (float)(dwSize/1024*100/1024/1024/1024)/100; 34 _stprintf_s(strSize,20,TEXT("%.2fT"),fSize);//文件大小 T 35 } 36 37 return strSize; 38 }
5 6 /*根据文件大小进行格式化 7 *@[in ] llBytes 文件的长度(B) 8 *@[out] pszSize 缓冲区 9 *@[in ] clen 缓冲区长度 10 */ 11 12 BOOL FileSizeToStringA(LONGLONG llBytes, char* pszSize, DWORD cLen) 13 { 14 double bytes = (double)llBytes; 15 DWORD cIter = 0; 16 char* pszUnits[] = { ("B"), ("KB"), ("MB"), ("GB"), ("TB") }; 17 DWORD cUnits = sizeof(pszUnits) / sizeof(pszUnits[0]); 18 19 // move from bytes to KB, to MB, to GB and so on diving by 1024 20 while(bytes >= 1024 && cIter < (cUnits-1)) 21 { 22 bytes /= 1024; 23 cIter++; 24 } 25 _snprintf_s(pszSize, cLen, _TRUNCATE,("%.2f %s"), bytes, pszUnits[cIter]); 26 return TRUE; 27 } 28 29 int main() 30 { 31 char szText[256]; 32 FileSizeToStringA(23156,szText,256); 33 34 cout << "szText:" << szText << endl; 35 36 getchar(); 37 return 0; 38 }