阅读FORTRAN二进制文件在C ++ [英] reading fortran binary file in c++
问题描述
阅读(用C ++程序)由FORTRAN code生成的二进制文件的问题已经问了很多次,并约定在FORTRAN记录令人满意的说明了(如的 http://local.wasp.uwa.edu.au/~pbourke/dataformats/fortran/ )
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/ )
然而,当我试图实现C ++程序,牢记FORTRAN公约它仍然无法正常工作。在这里,我想我们的二进制文件TEST.bin,烧写包含1个整数,由Fortran例程写成二进制格式。
这里是我尝试在C ++来阅读:
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;
}
下面的双重>> IVAL结构首先读取该Fortran记录的报头(它包含在字节的记录的大小)和第二>> IVAL应该提取的值。写在文件中的整数为8,但程序输出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.
下面是二进制文件的内容:
^ D ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ H ^ @ ^ @ ^ @ ^ D ^ @ ^ @ ^ @ ^ @ ^ @ ^ @ ^ @
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?
推荐答案
运营商的GT;&GT;
是的格式的输入操作符。它用于读取文本文件,所述文本重新presentation转换为二进制
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);
当然,你看了之后,你可能需要字节交换正确尾数重新presentation。
Of course, after you read it, you may need to byte swap for correct endian representation.
这篇关于阅读FORTRAN二进制文件在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!