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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM