//OS: LINUX Fedora17 3.3.4-5.fc17.i686.PAE
//HardWare:32byte
//ouput:
//t1.bin 's size:7000000
//t2.txt 's size:10000000
//Write size_t(-1) (the largest unsigned int on your platform) to a text file 1,000,000 times. Repeat,
// but write to a binary file. Compare the size of the two files, and see how much room is saved using the binary format. (You may first want to calculate how much will be saved on your platform.)
#include <iostream>
#include <fstream>
using namespace std;
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
size_t max=-1;
long ln = 1000000;
cout.setf(ios::showbase);
cout.setf(ios::uppercase);
cout.setf(ios::hex,ios::basefield);
cout <<"max: "<< max<<endl;
ofstream ofstrm("t1.bin",ios::binary|ios::out);
if(!ofstrm.is_open()){
cout << "File t1.bin open failure."<<endl;
return -1;
}
for(long i = 0; i<ln;++i)
ofstrm.write((char*)&max,strlen((char*)&max));
ofstrm.close();
ofstream ofstrm_txt("t2.txt",ios::out);
if(!ofstrm_txt.is_open()){
cout <<"File t2.txt open failure."<<endl;
return -1;
}
for( long i =0; i< ln; ++i)
ofstrm_txt << max;
ofstrm_txt.close();
struct stat buf;
stat("t1.bin",&buf);
cout.unsetf(ios::showbase);
cout.unsetf(ios::uppercase);
cout.setf(ios::dec,ios::basefield);
cout <<"t1.bin 's size:"<< buf.st_size<<endl;
stat("t2.txt",&buf);
cout <<"t2.txt 's size:"<<buf.st_size <<endl;
}
为什么二进制文件与文本文件存入同样的数据,文件大小差异会这么大?(from <<Thinking in C++>>'s execise)
最新推荐文章于 2024-11-07 16:28:09 发布
本文通过编写C++程序,将最大无符号整数写入文本文件和二进制文件各一百万次,并比较两种文件的大小,以此来展示使用二进制格式存储数据的优势。
2104

被折叠的 条评论
为什么被折叠?



