jacobwilliams / csv-fortran

Read and Write CSV Files Using Modern Fortran
Other
99 stars 44 forks source link

First array entry skipped when adding from array #9

Closed jg110 closed 2 years ago

jg110 commented 4 years ago

If csv_write_test.f90 is modified to construct an input array from array values, the first entry is ignored:

program csv_write_test

use csv_module
use iso_fortran_env, only: wp => real64

implicit none

type(csv_file) :: f
logical :: status_ok
real(wp), dimension(3) :: X = [1._wp, 2._wp, 3._wp]

! open the file
call f%open('test.csv',n_cols=4,status_ok=status_ok)

! add header
call f%add(['x','y','z','t'])
call f%next_row()

! add some data:
call f%add([X(1),X(2),X(3)],real_fmt='(F5.3)')
call f%add(.true.)
call f%next_row()
call f%add([4.0_wp,5.0_wp,6.0_wp],real_fmt='(F5.3)')
call f%add(.false.)
call f%next_row()

! finished
call f%close(status_ok)

end program csv_write_test

test.csv:

"x","y","z","t"
2.000,3.000,0.000,T
4.000,5.000,6.000,F
jg110 commented 4 years ago

This problem is fixed by adding two lines to csv_module.F90 starting at line 519 (surrounding lines added for context):

#if defined __GFORTRAN__
        ! This is a stupid workaround for gfortran bugs (tested with 7.2.0)
        select type (val)
        type is (character(len=*))
            call me%add(val(i),int_fmt,real_fmt,trim_str)
        type is (real(wp))
            call me%add(val(i),int_fmt,real_fmt,trim_str)
        class default
            call me%add(val(i),int_fmt,real_fmt,trim_str)
        end select

The fix is similar to the one added for character inputs. This bug is especially confusing to me because I tried adding another do loop with a select type statement for inputs of type real(wp) and everything I tried inside the statement to output the value of i and val(i) came out correctly. It's like the iterator is being incremented by one when the add subroutine is called.

jg110 commented 4 years ago

After further testing I've verified that this bug doesn't occur with the Intel Fortran compiler.

jacobwilliams commented 4 years ago

What version off the compiler are you using? I don't see this bug with gfortran 9.1.

Also note: this issue is similar to #4

What do you get when you run the updated test on #10

jg110 commented 4 years ago

I'm using gfortran 9.2.1 from the Fedora 31 package set. I'll try the updated test and report back.

jg110 commented 4 years ago

Sorry it took me a while to get back to this. I'm still getting this issue with the other branch when I replace csv_write_test.f90 with the program in my first post.

jg110 commented 2 years ago

Following up on this, it was a bug in older versions of gfortran. With a sufficiently new version (tested with 11.2.1) the above code will generate the correct CSV file:

"x","y","z","t"
1.000,2.000,3.000,T
4.000,5.000,6.000,F