简体   繁体   中英

simple c++ binary file reading

I have a binary file created by some fortran code. I want to write a c++ code to read this binary file and then spit it out through std::cout. Here is so far my code:

    #include<fstream>
    #include<iostream>

using namespace std;

int main(){
  ifstream file("tofu.txt", ios::binary | ios::in | ios::ate);
  ifstream::pos_type size;
  if(file.is_open()){
    size = file.tellg();
    cout << "size = " << size << '\n';
    file.seekg(0);
    char bar[500];
    file.read((char*) (&bar), size);
    file.close();
    string foo(bar);
    cout << "foo = " << foo << '\n';
  }
  else cout << "Unable to open file";
  return 0;
}

However, when compiled and run, the code gives me nothing:

size = 250
foo =

Could someone tell me where I'm doing wrong in the code? Thanks!

You forgot to terminate your char array, leading to undefined behaviour. Fix it like this:

char bar[500];
assert(size < 500);
file.read((char*) (&bar), size - 1);
bar[size] = '\0';

(Make sure you check that size isn't larger than you have space for, too!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM