Search code examples
fortranformattxt

Incorrect reading of a variable from a txt (Fortran)


I'm trying to read this txt:

Fecha   dia mes ano hora    min 

03/06/2016 00:00    3   6   2016    0   0   
03/06/2016 00:05    3   6   2016    0   5   
03/06/2016 00:10    3   6   2016    0   10  
03/06/2016 00:15    3   6   2016    0   15  
03/06/2016 00:20    3   6   2016    0   20  
03/06/2016 00:25    3   6   2016    0   25  
03/06/2016 00:30    3   6   2016    0   30  
03/06/2016 00:35    3   6   2016    0   35  
03/06/2016 00:40    3   6   2016    0   40  
03/06/2016 00:45    3   6   2016    0   45  
03/06/2016 00:50    3   6   2016    0   50  
03/06/2016 00:55    3   6   2016    0   55  
03/06/2016 01:00    3   6   2016    1   0

With the following code:

    program fecha
    implicit none
    integer, dimension(13):: dia, mes, ano, hora, minuto

    character*50 :: formato = '(11x,5x,1x,i1,1x,i1,1x,i4,1x,i1,1x,i2)'

    open (unit = 10, file = 'datos.txt')
    read(10,*)
    read(unit = 10, fmt = formato) dia, mes, ano, hora, minuto

    write(*,*) dia

    close(10)

    end program

Why this code read 'dia' in this way:

 3           6        2016           0           0           3           6        2016           0           5           3           6        2016

(I know how it's reading but not why)


Solution

  • You need to skip two lines at the beginning as well as reading the values line by line.

    The following example is a slight modification of your program which runs smoothly.

    program fecha
      implicit none
    
      integer               :: i, iounit
      integer, parameter    :: n = 13
      integer, dimension(n) :: dia, mes, ano, hora, minuto
    
      open (newunit = iounit, file = 'datos.txt')
      read (iounit, *)
      read (iounit, *)
    
      do i = 1, n
        read (unit = iounit, fmt = '(16x, i5, i4, i7, 2i5)') dia(i), mes(i), ano(i), hora(i), minuto(i)
        print *, dia(i), mes(i), ano(i), hora(i), minuto(i)
      end do
    
      close (iounit)
    end program
    

    My output is

    $ gfortran -g3 -Wall -fcheck=all a.f90 && ./a.out
               3           6        2016           0           0
               3           6        2016           0           5
               3           6        2016           0          10
               3           6        2016           0          15
               3           6        2016           0          20
               3           6        2016           0          25
               3           6        2016           0          30
               3           6        2016           0          35
               3           6        2016           0          40
               3           6        2016           0          45
               3           6        2016           0          50
               3           6        2016           0          55
               3           6        2016           1           0