C equivalent formatted list

I use Fortran, in which I used the namelist serial interface to get variables from a file. This allows me to have a file that looks like

&inputDataList n = 1000.0 ! This is the first variable m = 1e3 ! Second l = -2 ! Last variable / 

where I can name a variable by its name and assign a value, as well as a comment after that, to indicate what a variable is.

Downloading is very easy.
 namelist /inputDataList/ n, m, l open( 100, file = 'input.txt' ) read( unit = 100, nml = inputDataList ) close( 100 ) 

Now my question is: is there something similar in C? Or do I need to do this manually by breaking the string in '=' and so on?

+4
source share
2 answers

Here is a simple example that will allow you to read Fortran namelists from C. I used the namelist file that you indicated in the question, input.txt .

Fortran routine nmlread_f.f90 (note the use of ISO_C_BINDING ):

 subroutine namelistRead(n,m,l) bind(c,name='namelistRead') use,intrinsic :: iso_c_binding,only:c_float,c_int implicit none real(kind=c_float), intent(inout) :: n real(kind=c_float), intent(inout) :: m integer(kind=c_int),intent(inout) :: l namelist /inputDataList/ n,m,l open(unit=100,file='input.txt',status='old') read(unit=100,nml=inputDataList) close(unit=100) write(*,*)'Fortran procedure has n,m,l:',n,m,l endsubroutine namelistRead 

C, nmlread_c.c :

 #include <stdio.h> void namelistRead(float *n, float *m, int *l); int main() { float n; float m; int l; n = 0; m = 0; l = 0; printf("%5.1f %5.1f %3d\n",n,m,l); namelistRead(&n,&m,&l); printf("%5.1f %5.1f %3d\n",n,m,l); } 

Also note that n , m and l must be declared as pointers in order to pass them by reference to the Fortran procedure.

On my system, I will compile it with a set of Intel compilers (my gcc and gfortran years, don't ask):

 ifort -c nmlread_f.f90 icc -c nmlread_c.c icc nmlread_c.o nmlread_f.o /usr/local/intel/composerxe-2011.2.137/compiler/lib/intel64/libifcore.a 

Running a.out displays the expected result:

  0.0 0.0 0 Fortran procedure has n,m,l: 1000.000 1000.000 -2 1000.0 1000.0 -2 

You can edit the aforementioned Fortran procedure to make it more general, for example. to specify the name list file name and list name from program C.

+9
source

I checked the answer above in GNU compilers v 4.6.3 and worked fine for me. Here is what I did for the appropriate compilation:

 gfortran -c nmlread_f.f90 gcc -c nmlread_c.c gcc nmlread_c.o nmlread_f.o -lgfortran 
+3
source

Source: https://habr.com/ru/post/1490802/


All Articles