defining path for file in FORTRAN

Vijay picture Vijay · Apr 22, 2013 · Viewed 27.3k times · Source

In bash I could write a simple script like below; to read the content of a file in the folder as I define the path for the file using environment variable "fileplace"

#!/bin/bash

fileplace="/home/vijay/data1/process-folder1/"

cat $file/file1.dat

I would like to achieve the same like above in FORTRAN 90, by defining the path using variable. I want to do like this because my folder location path is long and I wanted to avoid using & and + symbol for long lines in FORTRAN 90.

I have tried writing simple FORTRAN 90 code as below for testing.

program test_read
implicit none

open (unit=10, status="old",file="/home/vijay/data1/process-folder1/file1.dat")
read(10,*) junk
write(*,*) junk 

stop
end

If can I want to avoid using the long path (/home/vijay/data1/process-folder1/) in the FORTRAN code. Is there any possibility to achieve this? If yes can anyone help to correct this FORTRAN code? Appreciate any help in advance.

Thank you

Vijay

Answer

Stefan picture Stefan · Apr 22, 2013

Fortran isn't a good language to work with strings, but this is still possible.

You need a variable, where you can store the path. If this path is a constant and already known at compile time, you can simply write

CHARACTER(*), PARAMETER :: fileplace = "/home/vijay/data1/process-folder1/"

The file can then be opened with

OPEN(unit=10, status="old",file=fileplace//"file1.dat")

If you want to change the path during execution time, you have to set a appropriate length for fileplace and adjust it accordingly, when you want to use it:

CHARACTER(100) :: fileplace

WRITE(fileplace,*) "/home/vijay/data1/process-folder1/"
OPEN(unit=10, status="old", file=TRIM(ADJUSTL(fileplace))//"file1.dat")

The functions ADJUSTL() and TRIM() move the content of string to the left to remove any leading whitespace and then cut all trailing whitespace.