2013-06-18 98 views
1

我想讀取一個二進制文件,其中包含一個開始sequenz char [9]和一個char [5] 5個ID。所以我打開我的文件,但我不知道如何正確保存我的數據。C++讀配置二進制文件

char[8] start_sq = "STARTSEQ\n" // start of the binary file 

之後有5個ID。

那麼,怎樣才能設置我的起點現在的位置是在start_sq

int current_pos = 0; 
std:ifstream readFile_; 
int *id; 
while((current_pos = (readFile_.tellg())) == eof) 
{ 
    //start after start_sq // not sure how to 
    int tmp_id = readFile_.read(reinterpret_cast<char*>(&id), sizeof(int)); // should be first ID (OR?) 
    ids.push_back(tmo_id); 
    // again for ID 2 

} 

我得到它後,如果我的問題是有點不清楚在第一。但我不知道如何正確實施。但正如你所看到的,我有一些想法/方法。

THX任何幫助:)

+0

我建議您閱讀:http://www.eecs.umich.edu/eecs/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html –

回答

1

是的,你會怎麼做:

[警告:以下是絕對沒有測試!]

//int current_pos = 0; 
std:ifstream readFile_; 

... // Open the file in binary mode, etc... 

//int *id; 
char id; 

// Read the 'STARTSEQ' string + 1 carriage return : 
char[9] startseq; 
readFile_.read(reinterpret_cast<char*>(&startseq[0]), 9); 
//             ^^^ 
// IMPORTANT : The above line shifts the current_pos of 9 bytes. 
// Short : readFile_.read(startseq, sizeof(startseq)); 

// Then read your IDs 
// You want your IDs as chars so let's read chars, not int. 
while(readFile_.good()) // or while(!readFile_.eof()) 
{ 
    readFile_.read(reinterpret_cast<char*>(&id), sizeof(char)); 
    // IMPORTANT : The above line shifts the current_pos of 1 byte. 
    // Short : readFile_.read(&id, 1); 
    ids.push_back(id); 
} 
// The above 'while' loops until EOF is reached (aka. 5 times). 
// See ifstream.good(), ifstream.eof(). 

注:string要讀取( 「STARTSEQ \ n」)是9個字符,而不是8

用於填充ids向量的另一種方法可能是:

vector<char> ids; 
int size = 5; 
ids.resize(size); 
// Read 'size' bytes (= chars) and store it in the 'ids' vector : 
readFile_.read(reinterpret_cast<char*>(&ids[0]), size); 

注:此處使用的編號爲while,但注意:不檢查是否已達到EOF。

我希望這是你在哪裏要求。