2013-07-10 43 views
4

我習慣於Fortran,其中我使用名單順序讀入來從文件中獲取變量。這使我有一個文件,它看起來像這樣C相當於Fortran名單

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

在那裏我可以通過命名它的名稱的變量,並分配一個值,以及事後的評論說出什麼變量實際上是。加載過程非常簡單

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

現在我的問題是,C中是否有類似的東西?或者我必須通過在'='處切斷字符串來手動完成,等等。

+0

我不熟悉Fortran,但我從來沒有聽說過這樣的事情用C – jozefg

+0

我不相信C有這樣的事情;但作爲一個附註,「NAMELIST」不一定是連續的。 –

+0

在C語言中沒有等價物。也許有人編寫了C代碼來做到這一點...你可以嘗試搜索。 –

回答

9

下面是一個簡單的例子,它可以讓你從C中讀取Fortran名單。我使用了在問題input.txt中提供的名稱列表文件。

的Fortran子程序nmlread_f.f90(請注意使用的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); 
} 

還要注意nml需要被聲明爲以便指針通過引用Fortran例程來傳遞它們。

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 

在我的系統與英特爾編譯器套件(我的gcc和gfortran是歲,不問)的編譯

您可以編輯上述Fortran程序以使其更通用,例如從C程序中指定名稱列表文件名和列表名。

3

我已經在GNU編譯器v 4.6.3下對上述答案進行了測試,併爲我完美工作。這裏的是我做了相應的編譯:

gfortran -c nmlread_f.f90 
gcc -c nmlread_c.c 
gcc nmlread_c.o nmlread_f.o -lgfortran