Question

I'm trying to write a rudimentary bit of code to print a 50*50 array called 'arr'. Unfortunately it so far only prints the first row of the array, although the formatting for that row is correct. I've attached the code below and was wondering if anyone could point out where I was going wrong? Thank you!

program testing

implicit none

integer :: i, j
integer, dimension (1:50, 1:50) :: arr

arr = 1

do i=1,50
  open(unit=6, file= "array.txt", action="write")
  write(6, '(2500I3)') (arr(i,j), j=1,50)
  close(6)
end do

end program testing
Was it helpful?

Solution

Your open statement is inside loop (along with a matching close statement). That means for every row of the array, you open the file. That's probably not what you meant to do.

The default position specifier for an OPEN statement if there is no POSITION specifier is 'ASIS'. For a file that already exists (your case after the first iteration, and perhaps even for the first iteration) that means that the position is unspecified. Your processor probably takes that to be the start of the file. That means that each iteration of the loop you simply overwrite the first record, over and over again.

If you must open the file each iteration, then use the POSITION='APPEND' specifier to position the file at the end when the open statement is executed. Otherwise, move the open and close statements out of the loop.

(The way that the default of 'ASIS' behaves means that you should always specify the initial position of a file via a POSITION specifier when executing an OPEN statement for an existing "on disk" file.)

OTHER TIPS

IanH's answer is correct. Your program can be fixed as follows. Note that output units should be parameterized and not set to 6 and that arrays and array sections can be written as shown.

program testing

implicit none

integer :: i
integer, dimension (1:50, 1:50) :: arr
integer, parameter :: outu = 20 ! better to parameterize unit and 
                                ! not to use the number 6, which most compilers
                                ! use for standard output

arr = 1
open(unit=outu, file= "array.txt", action="write")
do i=1,50
  write(outu, '(2500I3)') arr(i,:) ! can write array section without implied do loop
end do
close(outu)
end program testing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top