等价的C与Fortran名称列表 [英] C equivalent to Fortran namelist
问题描述
我习惯到Fortran中,我使用的读取顺序的namelist得到变量出文件。这使我有一个文件,它看起来像这样
I am used to Fortran in which I used the namelist sequential read in to get variables out of a file. This allows me to have a file which looks like this
&inputDataList
n = 1000.0 ! This is the first variable
m = 1e3 ! Second
l = -2 ! Last variable
/
在那里我可以命名被它的名字的变量,并分配一个值,以及事后的评论说出什么变量实际上是。加载由
where I can name the variable by it's name and assign a value as well as comment afterwards to state what the variable actually is. The loading is done extremely easy by
namelist /inputDataList/ n, m, l
open( 100, file = 'input.txt' )
read( unit = 100, nml = inputDataList )
close( 100 )
现在我的问题是,有没有任何C类似的事情?或者,我将不得不通过砍在'='等字符串做手工?
Now my question is, is there any similar thing in C? Or would I have to do it manually by chopping the string at the '=' and so on?
推荐答案
下面是一个简单的例子,可以让你读C.我用你在问题中提供的名称列表文件的Fortran名称列表, input.txt的
。
Here is a simple example that will let you read Fortran namelists from C. I used the namelist file that you provided in the question, input.txt
.
Fortran的子程序 nmlread_f.f90
(注意使用 ISO_C_BINDING
)
Fortran subroutine nmlread_f.f90
(notice 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);
}
另请注意, N
, M
和→
需要为了通过引用传递他们Fortran例程声明为指针。
Also notice that n
,m
and l
need to be declared as pointers in order to pass them by reference to the Fortran routine.
在我的系统与英特尔编译器套件(我的gcc和gfortran是岁,不问)的编译:
On my system I compile it with Intel suite of compilers (my gcc and gfortran are years old, 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
执行的a.out
产生预期的输出结果:
0.0 0.0 0
Fortran procedure has n,m,l: 1000.000 1000.000 -2
1000.0 1000.0 -2
您可以编辑上面的Fortran程序,使之更加普遍,例如从C程序指定名称列表的文件名和目录名。
You can edit the above Fortran procedure to make it more general, e.g. to specify namelist file name and list name from the C program.
这篇关于等价的C与Fortran名称列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!