Home>
Question

After counting the number of lines, I want to read the following data, but it doesn't work. For some reason only the last line is read.
How can I read the data properly?

Data I want to read

1, 3.88000000e-003, -9.50325916e-019, 3.00000000e-002
2, 3.88000000e-003, -9.50325916e-019, 0.00000000e + 000
3, -3.88000000e-003, 4.75162958e-019, 0.00000000e + 000
4, -3.88000000e-003, 2.49220638e-016, 3.00000000e-002
5, 3.22000000e-003, -7.88672539e-019, 3.00000000e-002
6, 3.22000000e-003, -7.88672539e-019, 0.00000000e + 000

Source code
program p4
  implicit none
  integer :: i, n
  real x, y, z, w
  open (17, file ='p5.txt', status ='old')
  n = 0
  read (17,'()')
  do
    read (17, *, end = 100)
    n = n + 1
  end do
100 continue
  rewind (17)
  read (17,'()')
  print *,'NumRec =', n
  do i = 1, n
    read (17, *) x, y, z, w
  end do
  close (17)
open (20, file ='p4.csv', status ='replace')
 do i = 1, n
  write (20, *) x, ",", y, ",", z, ",", w
 end do
close (20)
end program p4
result
6 3.22E-03 -7.89E-19 0
6 3.22E-03 -7.89E-19 0
6 3.22E-03 -7.89E-19 0
6 3.22E-03 -7.89E-19 0
6 3.22E-03 -7.89E-19 0
  • Answer # 1

    It is loaded, but each time it overwrites what I read last time, only the last one I read remains.

    Have you ever heard of an "array"? Use it to save everything.

  • Answer # 2

    x, y, z, wIs just a variable, not an array, and is overwritten every time in a read loop.
    (At the end of the read loopx, y, z, wContains the value of the last read row. )

    p4.csvWhat is written inx, y, z, w(The value of the last read line is stored) It is the number of lines read.

    Read array

    Is in the title, but it is not read into the array.
    Let's read it into an array and export the contents of the array when exporting.

  • Answer # 3

    program p3
    implicit none
    integer n, i
    real, dimension (70000,4) :: a! A sufficiently large number of lines has been set.

    open (17, file ='p3.txt', status ='old')
    n = 0

    do
    read (17, *, end = 100)
    n = n + 1
    end do

    100 continue
    rewind (17)

    print *,'NumRec =', n
    do i = 1, n
    read (17, *) a (i, 1), a (i, 2), a (i, 3), a (i, 4)
    end do
    close (17)

    open (20, file ='p3.csv', status ='replace')

    do i = 1, n
    write (20, *) a (i, 1),',', a (i, 2),',', a (i, 3),',', a (i, 4)
    end do

    close (20)
    end program p3

    I was able to read it when I teamed up with
    If there is a space at the beginning of the line, it will not read well ...