8

I'm writing in fortran (90). My program must read file1, do something with every line of it and write result to file2. But the problem - file1 has some unneeded information in first line.

How can I skip a line from input file using Fortran?

The code:

open (18, file='m3dv.dat')
open (19, file='m3dv2.dat')
do
  read(18,*) x
  tmp = sqrt(x**2 + 1)
  write(19, *) tmp
end do

First line is a combination of text and numbers.

osgx
  • 90,338
  • 53
  • 357
  • 513

3 Answers3

15

One possible solution has already been presented to you which uses a "dummy variable", but I just wanted to add that you don't even need a dummy variable, just a blank read statement before entering the loop is enough:

open(18, file='m3dv.dat')
read(18,*)
do
    ...

The other answers are correct but this can improve conciseness and (thus) readability of your code.

Simon
  • 31,675
  • 9
  • 80
  • 92
1

Perform a read operation before the do loop that reads whatever is on the first line into a "dummy" variable.

program linereadtest
implicit none
character (LEN=75) ::firstline
integer :: temp,n
    !
    !
    !
open(18,file='linereadtest.txt')
read(18,*) firstline
do n=1,4
   read(18,'(i3)') temp
   write(*,*) temp
end do
stop
end program linereadtest

Datafile:

This is a test of 1000 things that 10 of which do not exist

50
100
34
566

!ignore the space in between the line and the numbers, I can't get it to format

jonsca
  • 10,218
  • 26
  • 54
  • 62
  • how can I read `whatever` in fortran? First line have several space-separated strings and numbers. – osgx Apr 10 '11 at 12:37
  • 1
    Make a character array (LEN=100, or whatever). I believe `read` should read until the end of the line. – jonsca Apr 10 '11 at 12:39
0
open (18, file='m3dv.dat')
open (19, file='m3dv2.dat')
read(18,*) x // <---

do
  read(18,*) x
  tmp = sqrt(x**2 + 1)
  write(19, *) tmp
end do

The line added just reads the first line and then overwrites it with the seconde on the first iteration.

iehrlich
  • 3,572
  • 4
  • 34
  • 43
  • I think yours assumes the information on the first line of the file is of the same type as the second line. – jonsca Apr 10 '11 at 12:29
  • @jonsca: yes, I do assume, unless other claimed. – iehrlich Apr 10 '11 at 12:35
  • No, first line is not a single number, but a combination of numbers and texts – osgx Apr 10 '11 at 12:35
  • So you'd probably be better off reading the top line into a char array of appropriate length, otherwise you'll get a runtime error, I believe (assuming from line 2 on down are `integers` or `double precision`, etc.) – jonsca Apr 10 '11 at 12:37
  • yes (`string number string number`), but universal solution is welcome too. – osgx Apr 10 '11 at 12:39
  • @osgx: the universal solution is to read chars one by one in a loop intil you encounter '\0' char. There also can be a procedure which do this, sorta GetString() in C. – iehrlich Apr 10 '11 at 12:40
  • 1
    @suddnely_me there is no '\0' in Fortan – jonsca Apr 10 '11 at 12:52