可以直接从二进制文件Fortran,以读取的字节? [英] Can Fortran read bytes directly from a binary file?

查看:849
本文介绍了可以直接从二进制文件Fortran,以读取的字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想用Fortran语言来读取二进制文件。的问题是,它没有被Fortran的写入,所以它不具有记录长度的指标。所以平时未格式化的Fortran读将无法工作。

I have a binary file that I would like to read with Fortran. The problem is that it was not written by Fortran, so it doesn't have the record length indicators. So the usual unformatted Fortran read won't work.

我有一个想法,我可以偷偷摸摸并读取文件作为格式的文件,逐字节(或4字节由4个字节,真的)到一个字符数组,然后字符的内容转换成整数并通过传递函数或等价可怕漂浮声明。但是,这并不工作:​​我尝试一次读取4个字节,并根据从输出POS的询问语句,读跳过像6000字节左右,字符数组被装入垃圾。

I had a thought that I could be sneaky and read the file as a formatted file, byte-by-byte (or 4 bytes by 4 bytes, really) into a character array and then convert the contents of the characters into integers and floats via the transfer function or the dreaded equivalence statement. But this doesn't work: I try to read 4 bytes at a time and, according to the POS output from the inquire statement, the read skips over like 6000 bytes or so, and the character array gets loaded with junk.

所以这是一个没有去。有没有这种方法,我忘了一些细节?或者是有只是一个完全不同的,更好的方式用Fortran做到这一点? (顺便说一句,我也试着阅读到整数* 1 阵列和一个字节数组。即使这些codeS会编译,当它来读的说法, code坠毁。)

So that's a no go. Is there some detail in this approach I am forgetting? Or is there just a fundamentally different and better way to do this in Fortran? (BTW, I also tried reading into an integer*1 array and a byte array. Even though these codes would compile, when it came to the read statement, the code crashed.)

推荐答案

是的。

Fortran 2003的推出流接入到语言。在此之前,大多数处理器都支持等价的东西作为一个扩展,也许所谓的二元或类似的。

Fortran 2003 introduced stream access into the language. Prior to this most processors supported something equivalent as an extension, perhaps called "binary" or similar.

无格式的流访问强加文件中没有记录的结构。

Unformatted stream access imposes no record structure on the file. As an example, to read data from the file that corresponds to a single int in the companion C processor (if any) for a particular Fortran processor:

USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_INT
INTEGER, PARAMETER :: unit = 10
CHARACTER(*), PARAMETER :: filename = 'name of your file'
INTEGER(C_INT) :: data
!***
OPEN(unit, filename, ACCESS='STREAM', FORM='UNFORMATTED')
READ (unit) data
CLOSE(unit)
PRINT "('data was ',I0)", data

您可能仍然有字节序和数据类型的大小的问题,但这些方面都是独立的语言。

You may still have issues with endianess and data type size, but those aspects are language independent.

如果你正在写之前的Fortran语言标准2003则未格式化的直接访问阅读到一个合适的整数变量可能起作用 - 这是Fortran的处理器具体,但适用于许多当前的处理器

If you are writing to a language standard prior to Fortran 2003 then unformatted direct access reading into a suitable integer variable may work - it is Fortran processor specific but works for many of the current processors.

这篇关于可以直接从二进制文件Fortran,以读取的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆