簡體   English   中英

使用std :: find查找從二進制文件讀取的字符並將其轉換為std :: vector中的std :: string <string> 造成這種不可預測的行為?

[英]Using std::find to find chars read from binary file and cast to a std::string in a std::vector<string> creates this inpredictible behaviour?

抱歉,標題太長了。 我不知道如何用簡短的詞來形容。

您是否願意重現我遇到的問題?

您可以使用任何wav文件進行讀取。

我試圖在這里查詢wav文件中的塊,這是代碼的簡化版本,但是我認為如果有問題,可能足以重新創建。

我使用的是Mac,並使用g++ -std=c++11編譯。

當我運行這段代碼並且不包括std::cout << query << std::endl; 然后std::find(chunk_types.begin(), chunk_types.end(), query) != chunk_types.end()在所有迭代中均返回0。 但是我知道二進制文件包含其中一些塊。 如果我加入這行,那么它可以正常工作,但是那也是不可預測的,可以說有時候它可以正常工作。

我有點困惑,我在這里做錯什么了嗎?

#include <fstream>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector> 

int main(){    

    std::vector<std::string> chunk_types{
    "RIFF","WAVE","JUNK","fmt ","data","bext",
    "cue ","LIST","minf","elm1",
    "slnt","fact","plst","labl","note",
    "adtl","ltxt","file"};

    std::streampos fileSize;
    std::ifstream file(/* file path here */, std::ios::binary);
    file.seekg(0, std::ios::beg);

    char fileData[4];

    for(int i{0};i<100;i+=4){ //100 is an arbitrary number

        file.seekg(i);
        file.read((char*) &fileData[0], 4);
        std::string query(fileData);

        std::cout << query << std::endl;

        /* if i put this std::cout here, it works or else std::find always returns 0 */


        if( std::find(chunk_types.begin(), chunk_types.end(), query) != chunk_types.end() ){ 
           std::cout << "found " + query << std::endl; 
        } 

    }

return 0;

}

std::string query(fileData)fileData上使用strlen查找其終止0,但未找到1,因為fileData不以0終止導致堆棧堆棧並導致SIGSEGV

同樣, file.read可以讀取的符號少於預期的符號,必須使用gcount提取上次讀取的實際字符數:

解決方法:

file.read(fileData, sizeof fileData);
auto len = file.gcount();
std::string query(fileData, len);

一種更有效的解決方案是直接讀入std::string並繼續重用它以避免內存分配(如果沒有短字符串優化)並復制:

std::string query;
// ...
    constexpr int LENGTH = 4;
    query.resize(LENGTH);
    file.read(&query[0], LENGTH);
    query.resize(file.gcount());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM