C++读取二进制文件(某特定格式)

 

该格式也不复杂,就是一个二进制文件,格式为:
8个通道,每个通道2字节,都为整数,最后两个通道都是0x03FF == 1023d,文件中中若干个8通道。

有个小细节就是:下面代码中 

infile.read((char*)&usValues[i], SIZE_PER_CHANNEL);

这一行,开始第二个参数用的是sizeof(usValues[0]),运行结果没错,但是一想可能不妥,因为前提是short类型是2字节才行,而C++只规定了short不长于int类型,所以还是用常量2代替sizeof(short)更加妥当。

 

#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;



int _tmain(int argc, _TCHAR* argv[])
{
    const int ARR_SIZE = 8;
    const int SIZE_PER_CHANNEL = 2;
    unsigned short usValues[ARR_SIZE] = {0};
    
    const char* pFileName = "C:\\Users\\Administrator\\Desktop\\zzb.txt";

    ifstream infile(pFileName, ios::binary);
    if (! infile)
    {
        cerr << endl << "Read file error" << endl;
        return -1;
    }

    unsigned long ulCountOfLines = 0UL; //行数, 一行为8个通道

    while(! infile.eof())
    {
        for (int i = 0; i < ARR_SIZE; ++ i)
        {
            infile.read((char*)&usValues[i], SIZE_PER_CHANNEL);
            cout << usValues[i] << ", ";
        } //for 

        cout << " The " << ++ulCountOfLines << " line " << endl; 
    
    } //while


    cout << endl << endl << "*********** Read " << ulCountOfLines << " lines *************" << endl;   
    cout << endl << endl << "------------ Read Finish --------------" << endl;
    infile.close();
    
    return 0;
}

 

 

 

转载于:https://www.cnblogs.com/cuish/p/4143840.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值