0

I have a problem with writing results on a file in Fortran. Here's a code as an example:

program test

    implicit none
    real,dimension(5)    ::x
    integer              ::i

    x = (/1, 2, 3, 4, 5/)

    open(unit=40,file="test.dat")

    do i=1,5
        read(*,*)
        write(40,*)x(i)**2
    end do

    close(unit=40)

end program

This returns the file test.dat with the following

   1.00000000    
   4.00000000    
   9.00000000    
   16.0000000    
   25.0000000    

The do-loop advances as I press "Enter", and, in theory, every time the do-loop advances, it should write on the file the correspondent value of x(i)^2. However, after the first iteration, it doesn't write anything until the code as ended, at which point it writes the missing 4 other values.

I need the code to write the results "in real time" in each iteration, not all at once after the code has ended. Is that possible?

Thanks for the help.

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
MrEpic0
  • 11
  • 1
  • Look at the right side of the page where it says "Related" and the second item "How do I flush output to a file after each write with a gfortran Fortran 90 program". In other word, DUPE. – dave_thompson_085 Oct 22 '22 at 02:47
  • But while it is a dupe it is rather old and the best way to do it nowadays, `flush` as defined by the standard, is hidden away in a comment, and as the answers are currently written the poster might not take the best advice. So new answer in the old question and mark this as duplicate, or new answer here? I am not sure what is the correct etiquette, – Ian Bush Oct 22 '22 at 06:56
  • 1
    @IanBush, an explicit new answer on the first linked question would seem valuable. My view on closing as duplicate instead of answering here: other approaches are also valid - close/re-open, environment variable to control runtime, maybe even non-standard options (just joking) - and we'd either duplicate those here or point to other resources. Much better to close as duplicate and put all options in one place, with, if desired, comments here. (Of course, this question can be re-opened, even single handedly, by people who have different views.) – francescalus Oct 22 '22 at 08:08

0 Answers0