为什么二进制文件与文本文件存入同样的数据文件大小差异会这么大?能帮解释上为什么吗
为什么二进制文件与文本文件存入同样的数据文件大小差异会这么大?能帮解释下为什么吗?
问题入题。
from <<Thinking in C++>>'s execise
我的代码以及运行结果如下:
------解决思路----------------------
ofstrm.write((char*)&max,strlen((char*)&max));这句有问题吧
------解决思路----------------------
ofstrm.write((char*)&max,sizeof(max));
------解决思路----------------------
问题入题。
from <<Thinking in C++>>'s execise
我的代码以及运行结果如下:
//OS: LINUX Fedora17 3.3.4-5.fc17.i686.PAE
//HardWare:32byte
//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;
}
//result:
//t1.bin 's size:7000000
//t2.txt 's size:10000000
------解决思路----------------------
ofstrm.write((char*)&max,strlen((char*)&max));这句有问题吧
------解决思路----------------------
ofstrm.write((char*)&max,sizeof(max));
------解决思路----------------------