linqy的个人博客分享 http://blog.sciencenet.cn/u/linqy

博文

二进制文件的数据读取以及简单的数据处理操作

已有 2281 次阅读 2017-6-30 17:57 |个人分类:C++|系统分类:科研笔记| ⒓虻ナ?荽?

读取二进制文件中的数据,并计算最大值、最小值以及均值


#include <fstream>
#include <stdlib.h>
void main()
{
    //将数据写入二进制文件中
    char *f1path = "C:\Users\linqy\Desktop\ex1.dat";//文件的路径
    ifstream ifstr(f1path,ios::in | ios::_Nocreate | ios::binary);
    if (!ifstr)
    {
        cerr<<"file open failed!"<<endl;
        exit(1);
    }

    int xx,min,max,n = 0;
    float mean;

    //ifstr.seekg(0);//将文件指针移至文件开始的位置
    //if (ifstr.read((char*)&xx,sizeof(int)))
    //{
       // n++;
    //}
    //else
    //{//若文件为空,则返回
       // cerr<<"file is null "<<endl;
       // exit(1);
    //}
    //min = max = xx;
    //mean = (float)xx;
    //while (!ifstr.eof())
    //{
       // if (ifstr.read((char*)&xx,sizeof(int)))
       // {
       //     n++;
       //     if (xx > max)
       //     {
       //         max = xx;
       //     }
       //     else if (min > xx)
       //     {
       //         min = xx;
       //     }
       //     mean += xx;
       // }
    //}
    //mean /= n;

    ifstr.seekg(0,ios::end);//将文件指针移至文件尾
    int nn = ifstr.tellg()/sizeof(int);//按整形大小计算的文件长度
    if (nn == 0)
    {
        cerr<<"the file entered is null !"<<endl;
            exit(1);
    }
    ifstr.seekg(0);//将文件指针移至文件开始的位置
    ifstr.read((char*)&xx,sizeof(int));//读取第一个数到xx
    min = max = xx;
    mean = (float)xx/nn;

    for (size_t i = 1;i < nn; i++ )
    {
        ifstr.read((char*)&xx,sizeof(int));
        if (xx > max)
        {
            max = xx;
        }
        else if (xx < min)
        {
            min = xx;
        }
        mean += (float) xx/nn;//这个计算均值的方法不错!
    }

    cout<<"min = "<<min<<endl;
    cout<<"max = "<<max<<endl;
    cout<<"mean = "<<mean<<endl;

    cout<<"Action finished!"<<endl;
    system("pause");

}




https://blog.sciencenet.cn/blog-3134052-1063867.html

上一篇:将文件中不同的内容进行分离存放在两个文件中
下一篇:爆笑笑话段子精选
收藏 IP: 124.207.244.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-9-27 11:48

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部