AleN
AleN

Reputation: 75

Fortran - Write and Read from same file using formats

The program is very stupid, but it is just a test to understand how reading from files works in Fortran. I wrote the following example:

program manipolazione
implicit none 
integer, parameter :: codice = 10
integer, parameter :: massimo = 20
integer :: numero, quadrato
integer :: error, errore_lettura
integer :: indice

010 format (1x, 'Il quadrato di ', I0, 1x, 'e'' ', I0)   
020 format(1x, A) ! scrive generico messaggio
030 format(1x, A, 1x, I0) ! scrive errori con loro codice
open (unit = codice, File = "test.txt", iostat = error, status = 'replace', action = 'write')
controllo_apertura : if (error == 0) then 
    write(*, 020) "Comincio a scrivere sul file...\n"
    contatore : do indice = 1, massimo, 1
        numero = indice
        quadrato = numero ** 2
        write(codice, 010) numero, quadrato
    end do contatore
else controllo_apertura
    write(*,020) "Non siamo riusciti ad aprire il file..."
end if controllo_apertura
close(codice)

open (unit = codice, File = "test.txt", iostat = error, status = 'old', action = 'read')
controllo_apertura1 : if (error == 0) then
    write(*,020)"Comincia la lettura dei valori!\n"
    counter : do indice = 1, massimo, 1
        read(codice, 010, iostat=errore_lettura) numero, quadrato ! THAT'S THE PROBLEM
        errorelettura : if (errore_lettura > 0) then 
            write(*,030) "Abbiamo avuto un problema serio, ho letto male, error:",errore_lettura
        else errorelettura
            write(*, 010) numero, quadrato
        end if errorelettura
    end do counter
else controllo_apertura1
    write(*,020) "Non siamo riusciti ad aprire il file..."
end if controllo_apertura1
read(*,*)
end program manipolazione

I would like to read what I have just written and print it back. In brief, write with a certain format and then read those values. By reading the code you will understand for sure. I really don't know what to do at line 29.

Upvotes: 2

Views: 1394

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

You seem to be using this format statement

010 format (1x, 'Il quadrato di ', I0, 1x, 'e'' ', I0) 

on this write statement

read(codice, 010, iostat=errore_lettura) numero, quadrato ! THAT'S THE PROBLEM

Your problem arises from trying to use a format statement which contains character string edit descriptors. The latest standard notes that these are not valid for input; I expect earlier standards also ruled them out. They make perfect sense when writing but it's difficult to see how you want them to be interpreted on a read statement. I'd try

011 format (2I0)
...
read(codice, 011, iostat=errore_lettura) numero, quadrato 

and see what happens

Upvotes: 1

Related Questions