简体   繁体   English

Fortran:写入和读取格式化的文件

[英]Fortran: Writing and Reading Formatted Files

I have an array of floating point numbers and want to write the values to a file. 我有一个浮点数数组,想将值写入文件。 Then read them back. 然后读回去。

I am writing to the file as follows 我正在写入文件如下

Do k = 1, nk
  Do j = 1, nj
    Write (u,*) (lec(i,j,k), i = 1, ni)
  End Do
End Do

This writes the numbers as follows when ni = 5 , nj = 4 and nk = 2 . ni = 5nj = 4nk = 2时,其nj = 4如下。

1.1 1.2 1.3 1.4 1.5    
2.1 2.2 2.3 2.4 2.5
3.1 3.2 3.3 3.4 3.5
4.1 4.2 4.3 4.4 4.5
1.1 1.2 1.3 1.4 1.5    
2.1 2.2 2.3 2.4 2.5
3.1 3.2 3.3 3.4 3.5
4.1 4.2 4.3 4.4 4.5

I want to change the format of the output file in the following way 我想通过以下方式更改输出文件的格式

lec: 1.1 1.2 1.3 1.4 1.5    
+ 2.1 2.2 2.3 2.4 2.5
+ 3.1 3.2 3.3 3.4 3.5
+ 4.1 4.2 4.3 4.4 4.5
+ 1.1 1.2 1.3 1.4 1.5    
+ 2.1 2.2 2.3 2.4 2.5
+ 3.1 3.2 3.3 3.4 3.5
+ 4.1 4.2 4.3 4.4 4.5

How can I modify the code to get this form of output? 如何修改代码以获得这种形式的输出?

I read things the same way, but I read the values in lec only when I encounter key lec: in the file. 我以相同的方式读取内容,但仅在文件中遇到key lec:时才读取lec中的值。

 Do k = 1, nk
   Do j = 1, nj
     if(k.eq.1.and.j.eq.1)then
       write(u,'(a)',advance='no')'lec:'
     else
       write(u,'(a)',advance='no')'+'
     endif
     Write (u,*) (lec(i,j,k), i = 1, ni)
   End Do
  End Do

or 要么

 Do k = 1, nk
   Do j = 1, nj
     if(k.eq.1.and.j.eq.1)then
       write(u,'(a,99f4.1))'lec:',(lec(i,j,k), i = 1, ni)
     else
       write(u,'(a,99f4.1)')'+',(lec(i,j,k), i = 1, ni)
     endif      
   End Do
  End Do

the 99 can be any number larger than ni or * if your compiler supports it. 99可以是大于ni*任何数字,如果编译器支持的话。

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

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