通过读取二进制文件用C ++的错误 [英] Error by reading binary file with c++

查看:147
本文介绍了通过读取二进制文件用C ++的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在包含二进制文件读取字符 INT &安培; 双击后头部:

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;

我的阅读煤焦与 FID&GT;&GT; STR1 工作得很好。如果我尝试用 INT 来做到这一点莫名其妙地产生一种奇怪的行为。然后输出会

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?

由于已经提前。

推荐答案

的std ::运算符&GT;&GT;(的std :: istream的&放大器;,INT和放大器;)尝试解析的从字符流整数,它不读取二进制数据。您需要使用 STD: :istream对象::更多(的char *,性病:: streamsize可) 功能

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.

这篇关于通过读取二进制文件用C ++的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆