2013-02-07 37 views
0

我有以下程序调用ScorecommandlineC程序不读取来自命令行.dat文件

int main (int argc, char *argv[]) { 
    if (argc!=15) { 
     usage(); 
     exit(1); 
    } 

    int iArray[14]; 
    int i = 0; 
    while(1){ 
     if(scanf("%d",&iArray[i]) != 1){ 
     break; 
     } 
     i++; 
     if(i == 14) { 
     i = 0; 
     } 
    } 

    int age = atoi(iArray[1]); 
    int b_AF = atoi(iArray[2]); 
    int b_ra = atoi(iArray[3]); 
    int b_renal = atoi(iArray[4]); 
    int b_treatedhyp = atoi(iArray[5]); 
    int b_type2 = atoi(iArray[6]); 
    double bmi = atof(iArray[7]); 
    int ethrisk = atoi(iArray[8]); 
    int fh_cvd = atoi(iArray[9]); 
    double rati = atof(iArray[10]); 
    double sbp = atof(iArray[11]); 
    int smoke_cat = atoi(iArray[12]); 
    int surv = atoi(iArray[13]); 
    double town = atof(iArray[14]); 

    double score = cvd_femal(age,b_AF,b_ra,b_renal,b_treatedhyp,b_type2,bmi,ethrisk,fh_cvd,rati,sbp,smoke_cat,surv,town,&error,errorBuf,sizeof(errorBuf)); 
    if (error) { 
     printf("%s", errorBuf); 
     exit(1); 
    } 
    printf("%f\n", score); 
} 

在我所旨在用于对该程序中的ARGS .dat文件,但是,如果我键入:

cat testscandata.dat | ./ScorecommandLine 

该程序不读取作为程序参数的文件。我该如何解决这个问题?

感谢

+2

为什么不使用'./ScorecommandLine bash0r

+1

你正在扫描一切到一个整数数组,然后尝试将这些整数从字符串转换为... ints? – dreamlax

+0

@ bash0r - 不幸的是,这给了我同样的东西 - 只是等待用户输入 – brucezepplin

回答

4

你混淆了将输入传递给程序的两种不同方式。您可以通过调用命令行中的命令并列出参数将参数传递给main。例如:

./ScoreCommandLine 1 2 3 4 5 6 7 8 9 10 11 12 13 14 

这些参数将通过argv传递到main

也可通过管道输入到程序中通过stdin通过使用管道和重定向在数据发送:

SomeCommand | ./ScoreCommandLine 

这将需要的SomeCommand输出并使用它作为在ScoreCommandLinestdin流。你可以通过使用scanf等来读取它。

对于你的情况,你应该重写程序,以便你不希望所有的参数都通过命令行传入,或者你应该使用xargs实用程序将stdin转换为命令行参数:

xargs ./ScoreCommandLine < testscandata.dat 

希望这有助于!

+0

关于'xargs'的好消息! +1 –

1

这不会作为参数传递给程序通过,但它会被输送进./ScorecommandLine程序stdin - 你将能够通过scanf和类似的功能来读取它,但不能作为命令行参数。

您需要创建一个新的脚本来读取文件(或stdin),它将执行另一个程序,将它作为可执行参数传递。

检查完程序后,我建议您删除if (argc!=15),因为您正在读取stdinscanf,而不是在任何地方解析命令行参数。