在 Fortran 中混合编写 ascii 和二进制数据

Writing a mixof ascii and binary data in Fortran

我正在尝试为 vtk 文件格式数据编写如下所示的 ASCII 和二进制数据的混合。

我知道二进制或 ASCII 的区别必须在文件打开语句中进行(在 FORM='BINARY' 中,最好是:ACCESS='STREAM')。我不明白如何为我需要的格式编写文件。

我要输出的内容:

ascii keyword  
ascii keyword  
ascii keyword  
ascii keyword  
ascii keywords "variable value in ascii" ascii keywords   
.....SOME BINARY DATA ....
.....................

我在用什么:

write(fl) "# vtk DataFile Version 3.0"//CHAR(13)//CHAR(10)  
write(fl)"Flow Field"//CHAR(13)//CHAR(10)  
write(fl)"BINARY"//CHAR(13)//CHAR(10)  
write(fl)"DATASET UNSTRUCTURED_GRID"//CHAR(13)//CHAR(10)  
write(fl)"POINTS",npoints,"float"    -------------> gives value of npoints(example:8) in binary format

输出应该是什么:

# vtk DataFile Version 3.0
Flow Field
BINARY
DATASET UNSTRUCTURED_GRID
POINTS 8 Float
.....SOME BINARY DATA ....
.....................

输出是什么:

# vtk DataFile Version 3.0
Flow Field
BINARY
DATASET UNSTRUCTURED_GRID
POINTSÒ^O^@^@float
.....SOME BINARY DATA ....
...................

我会替换

write(fl)"POINTS",npoints,"float"

BLOCK
   integer, parameter :: big_enough = 132 ! Or whatever
   character(big_enough) line
   write(line,'(*(g0))')"POINTS ",npoints," Float"//achar(13)//achar(10)
   write(f1) trim(line)
END BLOCK

首先,您会在互联网上找到编写 VTK 文件的示例,例如问题 and in various open source research codes, like https://bitbucket.org/LadaF/elmm/src/866794b5f95ec93351b0edea47e52af8eadeceb5/src/simplevtk.f90?at=master&fileviewer=file-view-default (this one is my simplified example, there are many more) or in dedicated libraries, like http://people.sc.fsu.edu/~jburkardt/f_src/vtk_io/vtk_io.html(还有一个用于 XML VTK 文件的 VTKFortran 库)。

因此,即使您使用的是 Windows,您也不应在 VTK 二进制文件中使用 Windows 行结束约定。仅以 achar(10)(或来自 iso_fortran_envnew_line 常量)结束您的行。并且不要忘记二进制数据必须是 bigendian。上面的链接中有如何处理的示例。

第三,将一个整数放入一个字符串中,我们有大量的重复项。我的意思是 真的 很大。从这里开始 Convert integers to strings to create output filenames at run time,我会无耻地在那里推荐我的 itoa 函数,因为它会大大简化您的代码。

write(fl)"POINTS ",itoa(npoints)," float"