chap06/sample4.f90

サンプルコードのダウンロード

 1program sample
 2  implicit none
 3
 4  integer :: i, n, ios
 5  real(8), allocatable :: x(:), y(:), xx(:), yy(:)
 6
 7  n = 32
 8  write(*, fmt='("Array size for output = ", i5)') n
 9
10  allocate(x(n))
11  allocate(y(n))
12
13  do i = 1, n
14    x(i) = real(i, 8) / real(n - 1, 8)
15    y(i) = sin(4 * 3.1415_8 * x(i)) * cos(2 * 3.1415_8 * x(i))
16  enddo
17
18  !
19  ! バイナリ(unformatted)で出力(上書き)
20  !
21  open(unit=10, iostat=ios, file='binary.dat', action='write', &
22       & form='unformatted', status='replace')
23
24  if(ios /= 0) then
25    write(*, *) 'Failed to open file for output'
26    stop
27  endif
28
29  ! 配列サイズの出力
30  write(10) n
31
32  ! 配列の出力
33  write(10) x, y
34
35  close(10)
36
37  !
38  ! バイナリ(unformatted)で読み込み
39  !
40  open(unit=20, iostat=ios, file='binary.dat', action='read', &
41       & form='unformatted', status='old')
42
43  if(ios /= 0) then
44    write(*, *) 'Failed to open file for input'
45    stop
46  endif
47
48  ! 配列サイズを読み込む
49  read(20) n
50
51  allocate(xx(n))
52  allocate(yy(n))
53
54  ! 配列を読み込む
55  read(20) xx, yy
56
57  close(20)
58
59  ! データが等しいかどうかをチェックする
60  do i = 1, n
61    if(x(i) /= xx(i) .or. y(i) /= yy(i)) then ! 厳密に等しいハズ
62      write(*, *) 'Error !'
63      stop
64    endif
65  enddo
66
67  write(*, *) 'Binary read/write success !'
68
69  deallocate(x)
70  deallocate(y)
71  deallocate(xx)
72  deallocate(yy)
73
74  stop
75endprogram sample