Read files with ";" in Fortran

Asked

Viewed 797 times

3

I need to read an array where the data is separated/delimited for ;, but it keeps slipping.

This is the file layout for reading the data:

//EstacaoCodigo;NivelConsistencia;Data;Hora;MediaDiaria;MetodoObtencaoVazoes;Maxima;Minima;Media;DiaMaxima;DiaMinima;MaximaStatus;MinimaStatus;MediaStatus
88850000;2;08/01/1964;;1;1;;;;;;0;0;0
88850000;2;09/01/1964;;1;1;50.24;2.78;6.446;30;14;1;1;1
88850000;2;10/01/1964;;1;1;364.4;3.26;1.744.774;9;31;1;1;1
88850000;2;11/01/1964;;1;1;7.6;1.18;2.224;21;27;1;1;1
88850000;2;12/01/1964;;1;1;3.1;0.575;1.118.226;2;21;1;1;1
88850000;2;01/01/1965;;1;1;16.2;0.315;1.214.194;17;14;1;1;1
88850000;2;02/01/1965;;1;1;6.6;0.1762;0.6019143;3;21;1;1;1
88850000;2;03/01/1965;;1;1;63;0.127;6.706.581;28;10;1;1;1

The code I made was this:

program vazoes
implicit none

INTEGER, DIMENSION(3,80) :: a
INTEGER :: row,col,max_rows,max_cols
max_rows=3
max_cols=80

open(Unit = 11, file = 'vazoes.txt', status = 'old')
DO row = 1,max_rows
    READ(11,*) (a(row,col),col=1,max_cols)
END DO

PRINT *, a(1,:)
END PROGRAM vazoes

How to read this data using ?

1 answer

3

There are several possible strategies to read the file in csv format with delimiter ';' and separate read fields.

Below follows a commented example, which reads each line of the file and stores it in the variable linha_texto.

The looping that is just after reading the line, traverses each character of the line and looks for a ';' and, if found, stores the "last" value in an array item dados.

After this looping, all (78) columns are available in the array and are printed separately in the standard output (console).

PROGRAM vazoes

    IMPLICIT NONE

    INTEGER :: i

    ! A variavel status verifica se houve 
    ! algum erro ao abrir o arquivo
    INTEGER :: status = 0

    ! Contador de posições de campos e número de campos
    INTEGER :: posicao_campo = 0, campos = 0

    ! Aloca espaco para leitura de uma linha de texto
    CHARACTER*2048 :: linha_texto

    ! Aloca espaço para um registro do banco de dados (78 campos)
    CHARACTER*32, DIMENSION(78) :: dados

    ! Abre o arquivo
    OPEN(UNIT=15, IOSTAT=status, FILE='vazoes.txt', STATUS='OLD')

    ! Verifica se houve erro ao abrir o arquivo
    IF (status .GT. 0) THEN
        WRITE(*,*) "Erro ao abrir o arquivo!"
        ! Finaliza a execução se houve erro
        STOP
    ENDIF

    ! Looping de leitura do arquivo
    DO
        ! Lê uma linha completa (um registro)
        READ(15, '(A)', IOSTAT=status) linha_texto

        ! Verifica se chegou no final do arquivo...
        IF (status .LT. 0) THEN
            ! ...e sai do looping se finalizou
            EXIT
        ENDIF

        ! Separa os campos utilizando o ';' como delimitador
        posicao_campo = 1
        campos = 1

        DO i=1,LEN(linha_texto)
            ! se encontrar o ';'...
            IF (linha_texto(i:i) == ';') THEN                
                ! ...adiciona o campo no array 'dados'
                dados(campos) = linha_texto(posicao_campo:i-1)
                campos = campos + 1
                ! marca a posição do último ';' encontrado
                posicao_campo = i+1
            ENDIF            
        ENDDO

        ! Imprime cada campo em formato texto na saída padrão
        WRITE(*,*) 'Inicio'
        DO i=1,campos-1            
            WRITE(*,*) dados(i)
        ENDDO
        WRITE(*,*) 'Fim.'

    END DO

    ! Fecha o arquivo    
    CLOSE(UNIT=15, IOSTAT=status)    
    ! Verifica se houve erro ao fechar o arquivo    
    IF (status .GT. 0) THEN
        WRITE(*,*) "Erro ao fechar o arquivo!"
        ! Finaliza a execução se houve erro
        STOP
    ENDIF

END PROGRAM vazoes

The organization of the records read in the variable dados and the conversion of the data to the correct types (date, integer, etc.) needs to be implemented and depends on the processing goal you intend to implement in the program.

If the data file format changes, you need to change the program or implement a dynamic allocation strategy (e.g.: ALLOCATE) of arrays, which adapts to variable formats during runtime ('Runtime').

Browser other questions tagged

You are not signed in. Login or sign up in order to post.