reading fortran binary file in c++

2020-04-18 04:23发布

The problem of reading (with c++ program) binary file generated by fortran code has been asked many times and the satisfactory description of conventions in fortran records has been given (e.g. http://local.wasp.uwa.edu.au/~pbourke/dataformats/fortran/ )

However when I try to implement c++ program, keeping in mind fortran conventions it still does not work. Here I assume we that the binary file "test.bin" contains 1 integer and is written in binary format by fortran routines. Here is how I try to read it in c++:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ifstream file;
  file.open("test.bin", ios::in|ios::binary);
  if (file.is_open())
  {
    int ival;
    file >> ival >> ival;  cout<< ival<<endl;
   }
   return 0;
}

Here the double >>ival construction first reads the header of the fortran record (which contains the size of the record in bytes) and the second >>ival supposed to extract the value. The integer written in file is 8, but the program outputs 0, so it does not read the data properly.

Here is a content of the binary file: ^D^@^@^@^@^@^@^@^H^@^@^@^D^@^@^@^@^@^@^@

So my question - what am I doing wrong?

Here is what hex editor shows:

0000000: 0400 0000 0000 0000 0800 0000 0400 0000  ................
0000010: 0000 0000 0a                             .....

Any idea what that means?

2条回答
家丑人穷心不美
2楼-- · 2020-04-18 04:57

operator>> is the formatted input operator. It is used to read text files, converting the textual representation to binary.

You should be reading using unformatted input operations. Try this:

file.read(reinterpret_cast<char*>(&ival), sizeof ival);

Of course, after you read it, you may need to byte swap for correct endian representation.

查看更多
不美不萌又怎样
3楼-- · 2020-04-18 05:05

Open it in a hex editor and dig out the structure. Is the header size 16, 32, 64 or 128 bits and which end up is it?

Hex editor..

查看更多
登录 后发表回答