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

本文通过编写C++程序,将最大无符号整数写入文本文件和二进制文件各一百万次,并比较两种文件的大小,以此来展示使用二进制格式存储数据的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值