为什么二进制文件与文本文件存入同样的数据,文件大小差异会这么大?(from <<Thinking in C++>>'s execise)

来源:互联网 发布:mac拔出u盘 编辑:程序博客网 时间:2024/06/06 07:47
//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;}