2015-05-28 42 views
1

我有一個.idx文件,我想用C++讀取這個文件。該文件中的所有項目由\ 0分隔。我想獲得該項目列表。我試過如下實現它:如何在二進制文件中搜索「 0」?

while (file.read(buffer, sizeof buffer), chars_read = file.gcount()){ 

      string search_term = "\0";    
      string contentElement = buffer; 

      string::size_type foundoffset = contentElement.find(search_term); 

      if (foundoffset != string::npos){ 
       //Do something... 
      } 
     //code continue here. 
     ..... 
} 

但在C++中,「\ 0」被視爲無效,如果你有使用C++的經驗,請指點我如何做到這一點。請注意,這個idx文件是二進制文件。 謝謝!

回答

3

請勿在二進制文件上使用std::string。如果您使用原始字符數組,請在其中查找,例如使用std::find

例如:

const char* end = buffer + chars_read; 
const char* ptr = std::find(buffer, end, '\0'); 

if(ptr == end) { 
    // not found 
} 
else { 
    // ptr points to null character 
} 
+0

你能告訴我如何從上面的指針ptr開始提取文本。此外,idx文件具有一個元素的格式:word \ 0 - 4字節數 - 4字節數(\ 0是結束一個字的符號,一個4字節的數字,然後是另一個4字節的數字)。你能指導我如何獲取單詞,二進制文件中的數字嗎?非常感謝! – abelhoang

+0

我解決了這個問題。對於問太容易的問題抱歉!我是開發C++的新手 – abelhoang

3

如果buffer是一個字符陣列(例如char buffer[...]),則contentElement串的結構將只讀取直到buffer'\0'

然而,有一個std::string constructor它允許你設置的字符串長度,如果包含字符串可以包含嵌入的終止字符,您應該使用的內容:

std::string contentElement(buffer, chars_read); 

雖然你的目的,我建議你遠離std::string,並直接在緩衝區中搜索。例如std::find