Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining path for file in FORTRAN

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

like image 467
Vijay Avatar asked Dec 01 '22 21:12

Vijay


2 Answers

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.

like image 63
Stefan Avatar answered Dec 09 '22 09:12

Stefan


You can use some Fortran like this:

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

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

Note:

  1. In Fortran string concatenation is expressed by the operator //.
  2. You'll have to declare the character variable fileplace, something like

    character(len=:), allocatable :: fileplace

ought to do it.

Fortran 2003 introduced the standard procedure GET_ENVIRONMENT_VARIABLE which may also be of interest to you if your compiler implements it.

like image 36
High Performance Mark Avatar answered Dec 09 '22 09:12

High Performance Mark