Fortran For Fun 常用io操作之read_line

读取任意长度行

在读取文件中的某一行时,通常会先定义一个固定长度的字符变量 line(max_line_), 它的长度为一个固定大小 max_line_ , 如果实际文件中的字符长度超过max_line_,就会读不完整。而可变长度的字符串不可以直接从文件中读取,所以以下程序通过一个字符一个字符的读取,然后添加到可变长度字符上,实现了可变长度字符的直接读取。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
program learn_read_line
use, intrinsic :: iso_fortran_env, only: iostat_end
implicit none
character(:),allocatable :: line
integer :: ios, unit
open(newunit=unit,status='scratch')
write(unit,*) '!'//repeat('=',40) &
& //new_line('a')//'! this is fortran comment' &
& //new_line('a')//'; this is python inline comment' &
& //new_line('a')//'# this is python comment' &
& //achar(10)//' 0 1.0 2.0E-5 +3.2'
rewind(unit)
do
call read_line(unit,line,iostat = ios)
if(ios== iostat_end) exit
print *, trim(adjustl(line))
enddo
close(unit=unit)
contains
subroutine read_line(unit, line, iostat)
integer, intent(in) :: unit
character(:), allocatable :: line !< Line storage.
integer, intent(out), optional :: iostat
character :: ch !< Character storage.
integer :: ios
line = ''
do
read(unit, "(a)", advance='no', iostat=ios) ch
if(ios /= 0) exit
line = line//ch
enddo
if(present(iostat)) iostat = ios
endsubroutine read_line
end program learn_read_line

结果

1
2
3
4
5
!========================================
! this is fortran comment
; this is python inline comment
# this is python comment
0 1.0 2.0E-5 +3.2