1. 写入文本式文件
program ch0913
implicit none
integer, parameter :: n = 20
integer, dimension (1:n) :: x = 0
real, dimension (1:n) :: y = 0.0
integer :: i
real :: t, t1, t2, t3, t4, t5
character *30 :: comment
open (unit=10, file='ch0913.txt')
call cpu_time(t)
t1 = t
comment = ' Program starts '
print 120, comment, t1
do i = 1, n
x(i) = i
end do
call cpu_time(t)
t2 = t - t1
comment = ' Integer array initialised'
print 120, comment, t2
y = real(x)
call cpu_time(t)
t3 = t - t1 - t2
comment = ' Real array initialised'
print 120, comment, t2
do i = 1, n
write (10, 100) x(i)
end do
call cpu_time(t)
t4 = t - t1 - t2 - t3
comment = ' Integer write '
print 120, comment, t4
do i = 1, n
write (10, 110) y(i)
end do
call cpu_time(t)
t5 = t - t1 - t2 - t3 - t4
comment = ' Real write '
print 120, comment, t5
100 format (1x, i10)
110 format (1x, f10.0)
120 format (1x, a, 2x, f7.3)
end program
2. 写入二进制文件
program ch0914
!声明变量
implicit none
integer, parameter :: n = 6
integer, dimension (1:n) :: x = 0
real, dimension (1:n) :: y = 0.0
!声明长度为n的数组字符长度
character(len=6):: z
integer :: i,a
real :: t, t1, t2, t3, t4, t5, t6,t7,b
character *30 :: comment
!变量赋值
z='yuesuf'
a=1
b=1.1
!创建二进制文件
open (unit=10, file='ch0914.bin', form='unformatted')
!写入一个整数,一个实数
write (10) a
write (10) b
!调用无返回值的函数,分别为整数数组、实数数组、字符数组赋值
call cpu_time(t)
t1 = t
comment = ' Program starts '
print 100, comment, t1
do i = 1, n
x(i) = i
end do
call cpu_time(t)
t2 = t - t1
comment = ' Integer assignment '
print 100, comment, t2
y = real(x+0.1)
call cpu_time(t)
t3 = t - t1 - t2
comment = ' Real assignment '
print 100, comment, t3
call cpu_time(t)
t4 = t - t1 - t2 - t3
comment = ' Character assignment '
print 100, comment, t4
!把上面的数据写入二进制文件
!写入整数数组文件
write (10) x
call cpu_time(t)
t5 = t - t1 - t2 - t3 - t4
comment = ' Integer write '
print 100, comment, t5
!写入实数数组文件
write (10) y
call cpu_time(t)
t6= t - t1 - t2 - t3 - t4 - t5
comment = ' Real write '
print 100, comment, t6
!写入字符数组文件
write (10) z
call cpu_time(t)
t7= t - t1 - t2 - t3 - t4 - t5 - t6
comment = ' Character write '
print 100, comment, t7
100 format (1x, a, 2x, f7.3)
end program
integer、real通常是4个字节,数组长度为6。
1个字节=2个16进制字符,一个16进制位=0.5个字节。
(十六进制)18 00 00 00=(十进制)1*16+8=24(个字节)
character是一个字节,yuesuf六个字节。
3. 读二进制文件
program ch09141
implicit none
integer, parameter :: n = 6
integer, dimension (1:n) :: x
real, dimension (1:n) :: y
integer :: i,a
real ::b
character(len=n) ::z
! 读取二进制数据
open (unit=10, file='ch0914.bin', form='unformatted', status='old')
read (10) a
read (10) b
read (10) x
read (10) y
read (10) z
!数据输出
print *,"数组数据"
do i = 1, n
print *, x(i), y(i)
end do
print *,"单个数值"
print *,a,b
print *,"单个字符串"
print *,z
end program