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

  • 相关阅读:
    Verilog杂谈
    Hadoop家族学习路线图
    R语言中apply函数
    R语言数组array函数
    R语言列表list函数
    R语言多元素向量
    R语言提取字符串的一部分substring函数
    R语言改变大小写 toupper()和 tolower()函数
    R语言统计字符串的字符数ncahr函数
    R语言格式化数字和字符串format函数
  • 原文地址:https://www.cnblogs.com/cuish/p/4143840.html
Copyright © 2011-2022 走看看