简体   繁体   English

用c ++读取fortran二进制文件

[英]reading fortran binary file in c++

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 (eg http://local.wasp.uwa.edu.au/~pbourke/dataformats/fortran/ ) 已经多次询问由fortran代码生成的读取(使用c ++程序)二进制文件的问题,并且已经给出了fortran记录中的约定的令人满意的描述(例如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. 但是,当我尝试实现c ++程序时,记住fortran约定它仍然不起作用。 Here I assume we that the binary file "test.bin" contains 1 integer and is written in binary format by fortran routines. 这里我假设二进制文件“test.bin”包含1个整数,并由fortran例程以二进制格式编写。 Here is how I try to read it in c++: 以下是我尝试用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. 这里double >> ival构造首先读取fortran记录的标题(其中包含以字节为单位的记录大小),第二个>> ival应该提取值。 The integer written in file is 8, but the program outputs 0, so it does not read the data properly. 写入文件的整数为8,但程序输出0,因此无法正确读取数据。

Here is a content of the binary file: ^D^@^@^@^@^@^@^@^H^@^@^@^D^@^@^@^@^@^@^@ 这是二进制文件的内容:^ D ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ H ^ @ ^ @ ^ @ ^ D ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ @

So my question - what am I doing wrong? 所以我的问题 - 我做错了什么?

Here is what hex editor shows: 以下是hex编辑器显示的内容:

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

Any idea what that means? 知道这意味着什么吗?

operator>> is the formatted input operator. 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. 当然,在阅读之后,您可能需要进行字节交换以获得正确的字节序表示。

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? 标头大小是16,32,64或128位,最终是什么?

Hex editor.. Hex编辑器..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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