Error by reading binary file with c++

别等时光非礼了梦想. 提交于 2019-12-25 07:18:16

问题


I try to read in a binary file containing char and int & double after a header:

// open file
int pos = 0,n;
char str1,str2;

//string str;
ifstream fid(pfad.c_str(),std::ios::binary);
if (fid.good() != 1) {
    printf(" ++ Error: The elegant bunch file %s doesn't exist.\n",pfad.c_str());
    return 1;
}

// cut the header
while (pos<5) {
    if (fid.eof()) {
        printf(" ++ Error: elegant bunch file is strange\n");
        return 1;
    }

    fid >> str1;

    switch (pos) {
        case 0: str2 = '&'; break;
        case 1: str2 = 'd'; break;
        case 2: str2 = 'a'; break;
        case 3: str2 = 't'; break;
        case 4: str2 = 'a'; break;
    }

    if (str1 == str2){
        pos ++;
    } else {
        pos = 0;
    }
}

   // Read out the data
   fid.seekg(19,ios_base::cur);

std::cout << fid.tellg() << std::endl;
fid >> n;
std::cout << fid.tellg() << std::cout;


printf("\n\n%i\n\n",n);
printf("\nOK\n");
return 0;

My reading char with fid >> str1 works just fine. If I try to do this with a int it produces somehow a strange behaviour. The output then gets

813

-10x6c4f0484

0

Whereby the first number is the position in the file and the second one should be the same, but it looks like a pointer to me. Can anybody maybe try to clarify me confusion?

Thanks already in advance.


回答1:


std::operator>>(std::istream&, int&) tries to parse an integer from a stream of characters, it doesn't read binary data. You'll need to use the std::istream::read(char*, std::streamsize) function.



来源:https://stackoverflow.com/questions/15497519/error-by-reading-binary-file-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!