0

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.

LihO
  • 41,190
  • 11
  • 99
  • 167
magu_
  • 4,766
  • 3
  • 45
  • 79
  • 2
    *"Can anybody maybe try to clarify me confusion?"* - your question itself is written in very confusing way. Try to edit it to make it more clear what exactly your problem is please. – LihO Mar 19 '13 at 11:06

1 Answers1

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.

Michael Wild
  • 24,977
  • 3
  • 43
  • 43
  • Yes this is it. Although it seems rather strang to me that you have to do it like this. But then again my experiences are normaly more with high level languages. Thx for your answer – magu_ Mar 19 '13 at 13:01
  • I'd consider modern C++ to be a high-level language which allows you to go low-level if required ;-) Back to the issue: It's just a matter of semantics. There's no way for `operator>>` to know whether it should try to parse a string into a integer or whether it should read binary data. So it's up to you to know the API and its semantics. BTW: Also in the very-high-level language Python you have to call `file.read(nbytes)` for binary I/O. – Michael Wild Mar 19 '13 at 13:08