Timofey Kargin
Timofey Kargin

Reputation: 181

How to set Fortran variables from the input file?

I have an input file like this:

x = 1.5
y = 2.8
z = 9.4
x = 4.2

I want to set variable's values. So, I do this:

read(1,'(A)', IOSTAT=io) str        
if (io > 0) then !error
    write(*,*) 'Check input.  Something was wrong'
    exit
else if (io < 0) then !EOF
    exit
else !read new value
    do i=1,len_trim(str)
        if (str(i:i) == "=") str(i:i) = " " !replase "=" with spaces
    end do            

    read(str, *) curvar, curval

    SELECT CASE (curvar)
    CASE ("x")
        x = curval            
    CASE ("y")
        y = curval
    CASE ("z")
        z = curval
    END SELECT

Is it possible to set variable with name stored in "curvar" to be equal value from "curval" without "CASE SELECT"? I suppose that some easier way is exist. I need it because my program will have much more variables than three.

Upvotes: 1

Views: 621

Answers (1)

If you can change your file very slightly at the beginning and at the end, you can use a namelist. See, for example: http://jules-lsm.github.io/vn4.2/namelists/intro.html

&namelist_name
x = 1.5
y = 2.8
z = 9.4
/

with a simple Fortran code

namelist /namelist_name/ x, y, z

read(unit, nml = namelist_name)

Otherwise the answer is no, it is not possible to just assign a value to a variable with a certain name from a configuration file without parsing the name and using some conditional or select case or an array of pointers or something like that. The Fortran namelist I/O does that for your convenience.

Or there are libraries that can do similar work and allow configuration files of various forms. This answer discusses these options in the context of the command line arguments. There are various libraries for configuration files of various forms, but weather forecast and climate prediction models, for example, most often just use namelists. For my model I wrote my own parser, that gives more options for structured data, but it is not documented and would be harder to use for other people.

Upvotes: 2

Related Questions