首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为什么二进制文件与文本文件存入同样的数据文件大小差异会这么大?能帮解释上为什么吗

2012-12-31 
为什么二进制文件与文本文件存入同样的数据文件大小差异会这么大?能帮解释下为什么吗?问题入题。from Thi

为什么二进制文件与文本文件存入同样的数据文件大小差异会这么大?能帮解释下为什么吗?
问题入题。
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));
[解决办法]
引用:
谢谢,2位楼上。
我把有问题的代码更正了。
ofstrm.write((char*)&amp;max,sizeof(max)); 

输出结果为:
max: 0XFFFFFFFF
t1.bin 's size:4000000
t2.txt 's size:10000000

t1.bin(二进制)的结果我理解了,为4ByteX1,000,000=4,00……


对于t2.txt,写9时是一个字节,写68时是两个字节,写12345678时是8个字节,远远超过4个字节了。

热点排行