Extract Specified Line from File Using Fortran - fortran

I am trying to write a function that extracts a specified line from a given file. My function to do so takes two arguments:
fUnit: this is the numerical identifier of the given file.
fLine: this is the line number that I'd like to extract. If the value of this input is -1, then the function will return the last line of the file (in my work, this is the functionality I need the most).
I have wrapped this function inside a module (routines.f95), as shown:
module routines
contains
function getLine(fUnit, fLine)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Get the nth line of a file. It is assumed that the file is !
! numerical only. The first argument is the unit number of the !
! file, and the second number is the line number. If -1 is !
! passed to the second argument, then the program returns the !
! final line of the program. It is further assumed that each !
! line of the file contains two elements. !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
implicit none
integer, intent(in) :: fUnit, fLine
integer :: i
real, dimension(2) :: tmp, getLine
if (fline .eq. -1) then
do
read(fUnit, *, end=10) tmp
end do
else
do i = 1, fLine
read(fUnit, *, end=10) tmp
end do
end if
10 getLine = tmp
end function getLine
end module routines
To test this function, I set up the following main program (test.f95):
program test
use routines
implicit none
integer :: i
real, dimension(2) :: line
open(21, file = 'data.dat')
do i = 1, 5
line = getLine(21, i)
write(*, *) i, line
end do
close(21)
end program test
The file data.dat contains the following information:
1.0 1.00
2.0 0.50
3.0 0.33
4.0 0.25
5.0 0.20
This code is a simplified version of the one I've written, but it reflects all the errors I obtain in my primary code. When I compile the above code with the commands
gfortran -c routines.f95
gfortran -c test.f95
gfortran -o test test.o routines.o
I do not obtain any syntax errors. The output of the program gives the following:
1 1.00000000 1.00000000
2 3.00000000 0.330000013
3 5.00000000 0.200000003
At line 28 of file routines.f95 (unit = 21, file = 'data.dat')
Fortran runtime error: Sequential READ or WRITE not allowed after EOF marker, possibly use REWIND or BACKSPACE
Error termination. Backtrace:
#0 0x7f2425ea15cd in ???
#1 0x7f2425ea2115 in ???
#2 0x7f2425ea287a in ???
#3 0x7f242601294b in ???
#4 0x400ccb in ???
#5 0x4009f0 in ???
#6 0x400b32 in ???
#7 0x7f2425347f49 in ???
#8 0x400869 in ???
at ../sysdeps/x86_64/start.S:120
#9 0xffffffffffffffff in ???
I understand that the error is being thrown because the program tries to extract a line that is past the EOF marker. The reason for this is because the program is skipping every other line, and thus skipping over the last line in the program.
Could someone please help me to understand why my program is skipping every other line of the input file? I am unable to find the issue in my code.

The position of a connected external file is a global state. In this case, the function getline changes the position of the file after it has searched. The next time the function is called, searching commences from the position it was left.
What you see, then, is not so much "skipping" of lines, but:
in the first iteration, the first line is read;
in the second iteration, a line (the second) is skipped, then a line (the third) is read;
in the third iteration, two lines are skipped and a third is attempted to be read.
However, the third line in the third iteration (the sixth of the file) is after an end-of-file condition. You see the result of reading the fifth line.
To enable seeking as you desire it, ensure that you position the file at its initial point before skipping lines. The rewind statement places a connected file at its initial position.
Instead of rewinding, you may close the file and re-open with position='rewind' to ensure it is positioned at its initial point, but the rewind statement is a better way to reposition. If you re-open without a position= specifier you see an effect similar to position='asis'. This leaves the position in the file unspecified by the Fortran standard.

After the help from #francescalus, I can answer my own question. The issue with my code was that each time my main program iterated through the function, the position of the read statement picked up at the last location. Because of this, my program skipped lines. Here is my updated code:
test.f95
program test
use routines
implicit none
integer :: i
real, dimension(2) :: line
open(21, file = 'data.dat')
do i = 1, 5
line = getLine(21, i)
write(*, *) i, line
end do
line = getLine(21, -1)
write(*, *) -1, line
close(21)
end program test
routines.f95
module routines
contains
function getLine(fUnit, fLine)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Get the nth line of a file. It is assumed that the file is !
! numerical only. The first argument is the unit number of the !
! file, and the second number is the line number. If -1 is !
! passed to the second argument, then the program returns the !
! final line of the program. It is further assumed that each !
! line of the file contains two elements. !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
implicit none
integer, intent(in) :: fUnit, fLine
integer :: i
real, dimension(2) :: tmp, getLine
rewind(fUnit)
if (fline .eq. -1) then
do
read(fUnit, *, end=10) tmp
end do
else
do i = 1, fLine
read(fUnit, *, end=10) tmp
end do
end if
10 getLine = tmp
end function getLine
end module routines
data.dat
1.0 1.00
2.0 0.50
3.0 0.33
4.0 0.25
5.0 0.20
Compile with
gfortran -c routines.f95
gfortran -c test.f95
gfortran -o test test.o routines.o
The output of this program is
1 1.00000000 1.00000000
2 2.00000000 0.500000000
3 3.00000000 0.330000013
4 4.00000000 0.250000000
5 5.00000000 0.200000003
-1 5.00000000 0.200000003

Related

How can I create a function in Fortran, that reads from file and works with it [duplicate]

This question already has answers here:
Passing character strings of different lengths to functions in Fortran
(2 answers)
Closed 2 years ago.
I have a bunch of files, which contain numbers in rows. I need to write a function, that
reads from file for the first time to find amount of elements in file;
allocates an array and reads numbers from file into array;
returns an array
My function gets a string - name of the file - as an input.
So, the function that I wrote is:
function arrays_proc(name) result(arr)
character(len=128), intent(in) :: name
integer :: i, tmp, ios
character(len=30) :: line
double precision, dimension(:), allocatable :: arr
open(unit=09, file=name, status='old', iostat=ios)
if ( ios /= 0) stop "error opening file"
tmp = 0
do
read(09, '(A)', iostat=ios) line
if (ios /= 0) exit
tmp = tmp + 1
end do
allocate(arr(tmp))
rewind(09)
do i=1, tmp
read(09, '(A)') arr(i)
end do
close(09)
return
end function arrays_proc
Then, in the main program I write
...
real(8), dimension(:), allocatable :: points, potent
points = arrays_proc(trim('carbon_mesh.txt'))
potent = arrays_proc(trim('carbon_pot.txt'))
...
When I run my program, I get instant "error opening file".
I assume the problem is with names of files or how I put them in my function.
Anyway, I hope someone can help me
When compiling your code with a minimal program, GFortran prints the following warnings:
a.f90:4:25:
4 | points = arrays_proc(trim('carbon_mesh.txt'))
| 1
Warning: Character length of actual argument shorter than of dummy argument ‘name’ (15/128) at (1)
a.f90:5:25:
5 | potent = arrays_proc(trim('carbon_pot.txt'))
| 1
Warning: Character length of actual argument shorter than of dummy argument ‘name’ (14/128) at (1)
Trying to print the value of name inside arrays_proc shows that it is filled with garbage. So, guided by the warnings, you can try to change the length of the name parameter to *, which allows a string of any length to be used as input.
With that change, the function manages to open the files.
See also: Passing character strings of different lengths to functions in Fortran

Passing an allocated array from a SUBTROUTINE to the main program in Fortran

There are several threads with similar titles of mine, but I do not believe they are the same. One was very similar fortran pass allocated array to main procedure, but the answer required Fortran 2008. I am after a Fortran 90/95 solution.
Another very good, and quite similar thread is Dynamic array allocation in fortran90. However in this method while they allocate in the subroutine, they don't ever appear to deallocate, which seems odd. My method looks on the surface at least to be the same, yet when I print the array in the main program, only blank spaces are printed. When I print in the subroutine itself, the array prints to screen the correct values, and the correct number of values.
In the following a MAIN program calls a subroutine. This subroutine reads data into an allocatable array, and passes the array back to the main program. I do this by using small subroutines each designed to look for specific terms in the input file. All of these subroutines are in one module file. So there are three files: Main.f90, input_read.f90 and filename.inp.
It seems then that I do not know how to pass an array that is allocatable in program Main.f90 as well as in the called subroutine where it is actually allocated, sized, and then deallocated before being passed to program Main. This perhaps sounds confusing, so here is the code for all three programs. I apologize for the poor formatting when I pasted it. I tried to separate all the rows.
main.f90:
Program main
use input_read ! the module with the subroutines used for reading filename.inp
implicit none
REAL, Allocatable :: epsilstar(:)
INTEGER :: natoms
call Obtain_LJ_Epsilon(epsilstar, natoms)
print*, 'LJ Epsilon : ', epsilstar
END Program main
Next is the module with a subroutine (I removed all but the necessary one for space), input_read.f90:
module input_read
contains
!===============================================================
!===============================================================
Subroutine Obtain_LJ_Epsilon(epsilstar,natoms)
! Reads epsilon and sigma parameters for Lennard-Jones Force-Field and also
! counts the number of types of atoms in the system
!===============================================================
!===============================================================
INTEGER :: error,line_number,natoms_eps,i
CHARACTER(120) :: string, next_line, next_next_line,dummy_char
CHARACTER(8) :: dummy_na,dummy_eps
INTEGER,intent(out) :: natoms
LOGICAL :: Proceed
real, intent(out), allocatable :: epsilstar(:)
error = 0
line_number = 0
Proceed = .true.
open(10,file='filename.inp',status='old')
!=============================================
! Find key word LJ_Epsilon
!=============================================
DO
line_number = line_number + 1
Read(10,'(A120)',iostat=error) string
IF (error .NE. 0) THEN
print*, "Error, stopping read input due to an error reading line"
exit
END IF
IF (string(1:12) == '$ LJ_epsilon') THEN
line_number = line_number + 1
exit
ELSE IF (string(1:3) == 'END' .or. line_number > 2000) THEN
print*, "Hit end of file before reading '$ LJ_epsilon' "
Proceed = .false.
exit
ENDIF
ENDDO
!========================================================
! Key word found, now determine number of parameters
! needing to be read
!========================================================
natoms_eps = -1
dummy_eps = 'iii'
do while ((dummy_eps(1:1) .ne. '$') .and. (dummy_eps(1:1) .ne. ' '))
natoms_eps = natoms_eps + 1
read(10,*) dummy_eps
enddo !we now know the number of atoms in the system (# of parameters)
close(10)
Allocate(epsilstar(natoms_eps))
epsilstar = 0.0
!============================================================
! Number of parameters found, now read their values
!============================================================
if(Proceed) then
open(11,file='filename.inp',status='old')
do i = 1,line_number-1
read(11,*) ! note it is not recording anything for this do loop
enddo
do i = 1,natoms_eps
read(11,*) dummy_char
read(dummy_char,*) epsilstar(i) ! convert string read in to real, and store in epsilstar
enddo
close(11)
PRINT*, 'LJ_epsilon: ', epsilstar ! printing to make sure it worked
endif
deallocate(epsilstar)
END Subroutine Obtain_LJ_Epsilon
end module input_read
And finally the input file: filename.inp
# Run_Type
NVT
# Run_Name
Test_Name
# Pressure
1.0
# Temperature
298.15
# Number_Species
# LJ_epsilon
117.1
117.1
117.1
# LJ_sigma
3.251
3.251
3.251
END
And again, I can't figure out how to pass the allocated epsilstar array to the main program. I have tried passing an unallocated array to the subroutine from the main.f90, allocating it inside, passing it back, and deallocating it in the main.f90, but that did not work. I have tried it as the code currently is... the code works (i.e. is bug free) but it does not pass epsilstar from the subroutine where it correctly finds it and creates an array.
It turns out that the mistake I made was in deallocating the array in the subroutine before passing it to the main program. By NOT deallocating, the array was sent back fine. Also, I do not deallocate in the main program either.

Read signed exponential

I am having trouble reading exponential from a text file using Fortran.
The entry in the text file looks like the following
0.02547163e+06-0.04601176e+01 0.02500000e+02 0.00000000e+00 0.00000000e+00 3
And the code that I am using looks like the following
read(iunit,'(ES20.8,ES20.8,ES20.8,ES20.8,ES20.8,I2)') dummy1, dummy2, Thermo_DB_Coeffs_LowT(iS,1:3),temp
The error I am getting is
Fortran runtime error: Bad value during floating point read
How can I read these values?
Well here is what I usually do when it is too painful to hand edit the file...
CHARACTER(LEN=256) :: Line
INTEGER, PARAMETER :: Start = 1
INTEGER :: Fin, Trailing_Int, I
DOUBLE, DIMENSION(6) :: Element
...
Ingest_All_Rows: DO WHILE(.TRUE.)
READ(...) Line ! Into a character-string
<if we get to the end of the file, then 'EXIT Ingest_All_Rows'>
Start =1
Single_Row_Ingest: DO I = 1, 6
Fin = SCAN(Line,'eE')+3 !or maybe it is 4?
IF(I ==6) Fin = LEN_TRIM(Line)
READ(Line(Start:Fin),*) Element(I) !fron the string(len-string) to the double.
Line = Line((Fin+1):)
IF(I ==6) Trailing_Int = Element(6)
ENDDO Single_Row_Ingest
<Here we shove the row's 5 elements into some array, and the trailing int somewhere>
ENDDO Ingest_All_Rows
You will have to fill in the blanks, but I find that SCAN and LEN_TRIM can be useful in these cases

End of record error in file opening

I am currently writing a code to simulate particle collisions. I am trying to open as much files as there are particles (N) and then put the data for positions and velocities in each of these files for each step of the time integration (using Euler's method, but that is not relevant). For that, I tried using a do loop so it will open all the files I need - then I put all the data in them with a different do loop later - and then close them all.
I first tried just doing a do loop to open the files - but it gave errors of the type "file already open in another unit", so I did the following:
module parameters
implicit none
character :: posvel
integer :: i, j, N
real :: tmax
real, parameter :: tmin=0.0, pi=3.14159265, k=500.0*10E3, dt=10.0E-5, dx=10.0E-3, g=9.806, ro=1.5*10E3
real, dimension(:), allocatable :: xold, xnew, vold, vnew, m, F, r
end module parameters
PROGRAM Collision
use parameters
implicit none
write(*,*) 'Enter total number of particles (integer number):'
read(*,*) N
allocate(xold(N))
allocate(vold(N))
allocate(xnew(N))
allocate(vnew(N))
allocate(m(N))
allocate(F(N))
allocate(r(N))
xold(1) = 0.0
vold(1) = 0.0
m(1) = 6.283*10E-9
r(1) = 10E-4
xold(2) = 5.0
vold(2) = 0.0
m(2) = 6.283*10E-9
r(2) = 10E-4
write(*,*) 'Type total time elapsed for the simulation(real number):'
read(*,*) tmax
do i = 1, N
write(posvel,"(a,i3.3,a)") "posveldata",i,".txt"
open(unit=i,file=posvel, status="unknown")
end do
do i = 1, N
close(unit=i)
end do
END PROGRAM Collision
The last ten lines are the ones that regard to my problem.
That worked in codeblocks - it opened just the number of files I needed, but I'm actually using gfortran and it gives me and "end of record" error in the write statement.
How can I make it to execute properly and give me the N different files that I need?
P.S.: It is not a problem of compilation, but after I execute the program.
Your character string in the parameter module has only 1 character length, so it cannot contain the full file name. So please use a longer string, for example
character(100) :: posvel
Then you can open each file as
do i = 1, N
write(posvel,"(a,i0,a)") "posveldata",i,".txt"
open(unit=i,file=trim(posvel), status="unknown")
end do
Here, I have used the format i0 to automatically determine a proper width for integer, and trim() for removing unnecessary blanks in the file name (though they may not be necessary). The write statement can also be written more compactly as
write(posvel,"('posveldata',i0,'.txt')") i
by embedding character literals into the format specification.
The error message "End of record" comes from the above issue. This can be confirmed by the following code
character c
write(c,"(a)") "1"
print *, "c = ", c
write(c,"(a)") "23" !! line 8 in test.f90
print *, "c = ", c
for which gfortran gives
c = 1
At line 8 of file test.f90
Fortran runtime error: End of record
This means that while c is used as an internal file, this "file" does not have enough space to accommodate two characters (here "23"). For comparison, ifort14 gives
c = 1
forrtl: severe (66): output statement overflows record, unit -5, file Internal Formatted Write
while Oracle Fortran12 gives
c = 1
****** FORTRAN RUN-TIME SYSTEM ******
Error 1010: record too long
Location: the WRITE statement at line 8 of "test.f90"
Aborted
(It is interesting that Oracle Fortran reports the record to be "too long", which may refer to the input string.)

Number of lines of a text file

I'm trying to make a function that takes in a file name (i.e. "data.txt") and produces the number of lines of that file.
data.txt :
24 42
45 54
67 76
89 98
12 21
99 99
33 33
The below piece of code is my attempt to build a function that takes in the filename "data.txt" and produces the number of lines of the file. The first part (lines 1-12) of the code is defining the function and the second part (lines 14-19) is where I call the function in a program. The output of the below code is 1 rarther than 7 (look up - data.txt has 7 lines).
function count_lines(filename) result(nlines)
character :: filename
integer :: nlines
open(10,file=filename)
nlines = 0
do
read(10,*,iostat=io)
nlines = nlines + 1
if (io/=0) exit
end do
close(10)
end function count_lines
program myread
integer :: count_lines
print *, count_lines("data.txt")
end program myread
Attempt a debuging:
I think it has something to do with the do loop not working, but I'm unsure. I have changed the if statement to if (io>0) and this gives an output of 2, which I don't understand. At present I'm not getting an error outputs when I compile just the wrong output.
filename (the dummy argument) is only one character long. Anything might happen if you provide a longer one (usually it is capped, though).
This does not result in an error as you did not specify the status of the file, or even checked whether the operation was successful (In fact, you just created a new file d).
You can avoid this by using an assumed length string:
function count_lines(filename) result(nlines)
character(len=*) :: filename
! ...
open(10,file=filename, iostat=io, status='old')
if (io/=0) stop 'Cannot open file! '
function count_lines(filename) result(nlines)
implicit none
character(len=*) :: filename
integer :: nlines
integer :: io
open(10,file=filename, iostat=io, status='old')
if (io/=0) stop 'Cannot open file! '
nlines = 0
do
read(10,*,iostat=io)
if (io/=0) exit
nlines = nlines + 1
end do
close(10)
end function count_lines
[Increment after the check to ensure a correct line count.]
For the second part of your question:
Positive (non-zero) error-codes correspond to any error other than IOSTAT_END (end-of-file) or IOSTAT_EOR (end-of-record). After reading in the (new) file in the first round of the loop (io==IOSTAT_END, I checked with my compiler), you are trying to read beyond the end... This results in a positive error. Since the increment occurs before you exit the loop, the final value is 2.