0

How can I read from a parent directory using the OPEN clause? Let's say

OPEN (11,file='../inf/input.dat',form='formatted',status='old') 

, which doesn't work. I get:

forrtl: severe (29): file not found, unit 11, file /home/cg/compile/comp/../inf/input.dat

I would like to read from the parent directory just before inf. Is that possible?

Peter
  • 71
  • 6
  • I update the post! – Peter Jul 16 '17 at 16:23
  • 1
    You can not do that directly in fortran. you need to obtain the current directory as a string and do the manipulation yourself. See here https://stackoverflow.com/q/30279228/1004168 – agentp Jul 16 '17 at 16:50
  • Sorry, I am bit unexperienced with FORTRAN. How could I do that? Should I include cd somewhere or you mean "strictly manually"? – Peter Jul 16 '17 at 17:54
  • 4
    This is platform specific, but you typically use `..` to reference a parent directory in a file name, as you have. I'll guess that the file you are trying to read from isn't actually where you think it is, or access to it is restricted in some way. – IanH Jul 16 '17 at 19:17
  • I would agree with @IanH -- I'd copy and paste the whole `/home/cg/compile/comp/../inf/input.dat` into an `ls` to see whether that program finds that file. – chw21 Jul 17 '17 at 02:24
  • could be duplicate of https://stackoverflow.com/questions/17210015/fortran-90-filelocation-filename? – Dr.Raghnar Jul 18 '17 at 14:43

1 Answers1

1

Unfortunately there is no unique way to do this, since paths are OS dependent. In order to this in a robust way you might need to define a function that look for the OS while preprocessing (cf. compilation flags e.g. here).

For *nix systems (Unix, including OSX, and Linux) the option you provided should suffice

../

in the path goes to the previous directory.

However in windows there is no way that I know to go in the above directory (I don't have a Windows system with me at the moment). However you can workaround this limitation with the GetModuleFileName API function. (note that this will not work in the systems above)

CHARACTER*(*) pathname          ! full name  
INTEGER       L                 ! length  
L= GetModuleFileName(NULL,pathname,LEN(pathname))

Fullname will now contain the full path where you run your program, so you can do all sort of string operation you want. If you want to go above one level

Idx = index(trim(pathname), '/', .True.)

Finds the index of the last '/' character in the pathname (you might need to look for the one before the last).

outfile_path=pathname(:idx)+'/inf/input.dat'

will be now the path you want.

Dr.Raghnar
  • 294
  • 3
  • 12