Skip to main content

File Utilities

Helper functions for common file operations.

file_exists

Check whether a file exists on disk.

logical :: exists
exists = file_exists(filepath)
ParameterTypeDescription
filepathcharacter(*)Path to the file

Returns: .true. if the file exists, .false. otherwise.

numRows

Count the number of lines (rows) in an open file unit.

integer :: nrows
nrows = numRows(fileunit)
ParameterTypeDescription
fileunitintegerFortran file unit number (file must already be open)

Returns: Number of lines in the file (integer). Rewinds the file unit after counting.

Code Example

program main
use fpl
implicit none

character(200) :: filepath
integer :: nrows
logical :: exists

filepath = "database/data.txt"

! Check if the file exists
exists = file_exists(filepath)

if (exists) then
write(*,*) "File found: ", trim(filepath)

! Open the file and count lines
open(100, file=filepath, status="old")
nrows = numRows(100)
write(*,*) "Number of rows: ", nrows
else
write(*,*) "File not found: ", trim(filepath)
end if
end program main

Compile & Run

gfortran -o fileutils.out fileutils.f90 -I/usr/lib64/gfortran/modules/ -lFPL
./fileutils.out