zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    2019 湖湘杯 Reverse WP
    2017第二届广东省强网杯线上赛--Nonstandard
    2019 上海市大学生网络安全大赛 RE部分WP
    2019 360杯 re wp--Here are some big nums
    MATLAB图像的代数运算
    编辑和剪绳子-头条2019笔试题
    奖品分配-头条2019笔试题
    TrajPreModel
    multiheadattention-torch
    腾讯笔试题-邻值查找
  • 原文地址:https://www.cnblogs.com/cuish/p/4143840.html
Copyright © 2011-2022 走看看