Pradeep Kumar Jha
Pradeep Kumar Jha

Reputation: 877

Starting reading from specific line numbers in Fortran

I have a file with 1000s of numbers like:

0000
0032
1201
:  :
:  :
:  :
2324

Depending on an input parameter "n", I want to read "m" numbers from this file from line numbers "n" to "n+m-1".

Any ideas how can I do this in Fortran?

Upvotes: 3

Views: 13692

Answers (2)

BaRud
BaRud

Reputation: 3218

I don't know if you have tried it yourself, but here is an minimal example: say, your input file looks like this:

0000
0032
1201
1234
4567
7890
2324

use this code (after reading it)

Program jhp
Implicit None
integer :: i
integer, parameter :: &
     m=7, &    !total number of line
     n=4, &    !line to skip
     p=3      !lines to read
integer,dimension(m)::arr   !file to read

open(12,file='file_so',status='old')
do i=1,n
  read(12,*)arr(i)
end do
do i=1,p
  read(12,*)arr(i)
  write(*,*)arr(i)
end do
End Program jhp

This skips first n line, and reads p lines after that. Hope that helps

Upvotes: 4

BaRud
BaRud

Reputation: 3218

may be,

open (unit, file ...)
do i=1,n
 read(unit,*) crap
end do

do i =n,n+m-1
 read(unit,*) whatever
end do
close(unit)

is what you are looking for. this is untasted, but may give you a go.

edit: direct access is better for this type of job: Just realised, though this is the easiest one, not the preferred one. You can open the file in direct access mode and complete your job as:

OPEN( unit, file, ACCESS='DIRECT', RECL=100, FORM='FORMATTED')

READ( unit, *, REC=n, ERR=10 ) x

Upvotes: 1

Related Questions