How to remove leading space when printing with write?

user3892863 picture user3892863 · Jul 30, 2014 · Viewed 12.8k times · Source

Suppose I have the following code

program fortran
  open(900, FILE='SOMETHING')   
  write(900, *) '21'    
end program fortran

The file form will be

 21

that is, there is a space before the number. How to get rid of that space?

Answer

Alexander Vogt picture Alexander Vogt · Jul 30, 2014

You can write it as a string:

PROGRAM fortran 

  OPEN(900,FILE='SOMETHING')
  WRITE(900,'(a)') '21'

END PROGRAM FORTRAN
> cat SOMETHING 
21

To respond to the comment:

The more explicit way of doing that would be to write the number into a string (you could also use list-directed I/O for this step), remove whitespaces from the string trim and finally output the left-adjusted adjustl:

program test
  character(len=23) :: str

  write(str,'(ES23.15 E3)') 1.23d0
  write(*,'(a)') adjustl(trim(str))

  write(str,'(ES14.7 E2)') 0.12e0
  write(*,'(a)') adjustl(trim(str))
end program
> ./a.out 
1.230000000000000E+000 
1.2000000E-01

This solution is probably more complicated then necessary, but it is a very flexible approach that can be extended easily for arbitrary purposes and formats.