mercredi 6 mars 2019

Using std::find to find chars read from binary file and cast to a std::string in a std::vector

Sorry for the long headline. I couldn't know how to describe it in short words.

Would you care to recreate the problem i am going through?

You can use any wav file to read.

I am trying to query the chunks in a wav file here, this is the simplified version of the code, but i think it might be enough to recreate if there is a problem.

I use a mac, and compile with g++ -std=c++11.

When i run this code and don't include the line std::cout << query << std::endl; then std::find(chunk_types.begin(), chunk_types.end(), query) != chunk_types.end() returns 0 in all iterations. But i know the binary file contains some of these chunks. If i include the line then it works properly, but that is also not predictable lets say it works properly sometimes.

I am a bit perplexed am i doing anything wrong here?

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

}

Aucun commentaire:

Enregistrer un commentaire