A question, I have a csv file called data.txt, I want to read it.
The data.txt is below
Vostok 1,1961,Yuri Gagarin Vostok 2,1961,Gherman Titov Vostok 3,1962,Andriyan Nikolayev Vostok 4,1962,Pavel Popovich Vostok 5,1963,Valery Bykovsky Vostok 6,1963,Valentina Tereshkova
I read the website below
In the " Reading CSV Files" section it describes how to read csv file using type.
From it I wrote my small code as below,
program main implicit none type :: mission_type character(len=8) :: name integer :: year character(len=20) :: pilot end type mission_type type(mission_type), allocatable :: missions(:) integer :: fu, rc, i, j open (action='read', file='data.txt', iostat=rc, newunit=fu) if (rc /= 0) stop i = 0 do ! get the size of missions(:) read (fu, *, iostat=rc) if (rc /= 0) exit i = i + 1 enddo allocate(missions(i)) rewind(fu) do j = 1,i ! read from data.txt read (fu, *, iostat=rc) missions(j) ! it uses * as the format. if (rc /= 0) exit end do close (fu) print *, missions(1)%name print *, missions(1)%year print *, missions(1)%pilot end program main
I expect the output should be
Vostok 1 1961 Yuri Gagarin
However, obviously, fortran recognize the space also as a delimitator, and therefore the result below is not what I wanted,
Vostok 1 1961
Does anyone have suggestion as how to read this csv file correctly?
Thank you very much in advance!
There is a stack overflow answer for a similar issue, it suggests read the whole line first, then do something further. Is there better way?