Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer, | intent(in) | :: | index | |||
integer, | intent(in) | :: | file_id |
function read_csv_item(index, file_id) result(column)
! Return the index'th item from the next line of file_id and move to next line
! Raise error if number of items not found
integer, intent(in) :: index, file_id
character(len=read_line_buffer_size) :: column
character(len=read_line_buffer_size) buffer
character(len=read_line_buffer_size*2) scanpart
logical column_not_found
integer ic, iostat, ie
scanpart = ''
column_not_found = .True.
ic = 0
iostat = 0
do while (column_not_found .and. iostat == 0)
read(file_id, "(a)", advance="no", iostat=iostat) buffer
scanpart = trim(adjustl(scanpart))//buffer
ie = 1
do while (column_not_found .and. ie > 0)
ie = scan(scanpart, ",")
if (ie > 0) then ! comma found
ic = ic + 1
column_not_found = ic /= index
if (.not. column_not_found) column = trim(adjustl(scanpart(:ie-1)))
scanpart = scanpart(ie+1:)
else if (iostat < 0 .and. ic+1 == index) then ! last item
column = trim(adjustl(scanpart))
column_not_found = .False.
end if
end do
end do
if (column_not_found) then
! TODO error if not found, e.g. because end of file or line
else
! Move to next line if not already
if (iostat == 0) read(file_id, "(a)")
end if
end function read_csv_item