Using fortran to convert between unformatted binary data and .txt format

Viewed 91

I'm currently working with a code/program (written in Fortran) where I need to provide some data in binary format. I am completely new to Fortran and also storing data in binary format. So currently, I'm trying to understand how I can convert the binary information to a readable .txt file, so I can ensure I store it the correct way.

Take for example the following code:


program data_to_bin
integer :: i
real(kind=8) :: x
integer(kind=1) :: spherical, linear, even
spherical = 1
linear = 0
even = 0
open(1,file="5data",form="unformatted")
write(1) spherical,linear,even
do i = 1, 5
    read(*,*) x
    write(1) x
    write(*,*) i, x
end do
close(1)
end program data_to_bin

If I run ./a.out <data.txt (where data.txt consist of a column with 5 numbers), then I create the file "5data".

But how do I read this file again? I tried writing the following code:

program bin_to_data
integer :: i
character :: x
open(1,file="5data.txt",form="formatted")
do i = 1, 8
    read(*,*) x
    write(1) x
    write(*,*) i, x
end do
close(1)
end program bin_to_data

If I enter ./a.out <5data in the terminal I get the error message "At line 7 of file bin_to_data.f90 (unit = 1, file = '5data.txt') Fortran runtime error: Missing format for FORMATTED data transfer".

0 Answers
Related