C++读取存储float文件(txt文件和二进制文件)

读文件采用ifstream,写文件用ofstream,这两个类包含在#include <fstream>中。

读取和写入存有float数据的txt文件

    long int number=0;
    ifstream ifile;     //说明输入文件流对象ifile
    ofstream ofile;     //说明输出文件流对象ofile
    float a=0;
    ifile.open( "a.txt" );
    ofile.open("b.txt");

    while(1){
        ifile>>a;                       //由文件读入数据
        ofile_txt<<a<<" ";
        number++;
        if(ofile_txt.eof()!=0) break;  //当读到文件结束时,ifile.eof()为真
        //cout<<a<<endl;     //屏幕显示
    }
    ifile.close();
    ofile.close();
    cout<<"total numbers:"<<number<<endl;

读取和写入存有float数据的二进制文件

    long int number=0;
    ifstream ifile;     //说明输入文件流对象ifile
    ofstream ofile;     //说明输出文件流对象ofile
    float a=0;
    ifile.open( "a.bat",ios::binary) );
    ofile.open("b.bat",ios::binary));

    float b;
    while (ifile.peek()!=EOF) {
        number++;
        ifile.read((char*)&b, sizeof(b));
        ofile.write((char*)&b, sizeof(b));
    }
    ifile.close();
    ofile.close();
    cout<<"total numbers:"<<number<<endl;

注意:对于二进制文件不能直接用eof()来作为是否到文件尾的判断。需要用peek()函数,peek的意思是看看下一个字符,指针不移动。

文件的打开模式

文件操作时,如果不显示指定打开模式,文件流类将使用默认值。
在 中定义了如下打开模式和文件属性:
ios::app // 从后面添加
ios::ate // 打开并找到文件尾
ios::binary // 二进制模式I/O(与文本模式相对)
ios::in // 只读打开
ios::out // 写打开
ios::trunc // 将文件截为 0 长度
可以使用位操作符 OR 组合这些标志,比如
ofstream logFile(“log.dat”, ios::binary | ios::app);

Reference:
http://blog.csdn.net/lightlater/article/details/6364931
http://blog.csdn.net/hankai1024/article/details/8016374
http://blog.csdn.net/step__by__step/article/details/6866627
http://www.cplusplus.com/reference/istream/istream/peek/

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值