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

查看:20
本文介绍了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 字节 x 4 字节,真的)读取为字符数组,然后将字符的内容转换为整数并通过传递函数或可怕的等价语句浮动.但这不起作用:我尝试一次读取 4 个字节,根据 inquire 语句的 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 中是否有一种完全不同且更好的方法来做到这一点?(顺便说一句,我也尝试读入一个 integer*1 数组和一个字节数组.即使这些代码可以编译,当涉及到 read 语句时,代码崩溃了.)

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.

未格式化的流访问对文件没有记录结构.例如,从对应于特定 Fortran 处理器的配套 C 处理器(如果有)中的单个 int 的文件中读取数据:

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天全站免登陆