C程序无法从命令行读取.dat文件

时间:2013-02-07 23:48:46

标签: c command-line-arguments

我有以下名为Scorecommandline的程序:

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);
}

其中我有一个.dat文件,打算用于此程序中的args,但如果我键入:

cat testscandata.dat | ./ScorecommandLine

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

由于

2 个答案:

答案 0 :(得分:4)

您将输入传递到程序中的两种不同方式令人困惑。您可以通过从命令行调用命令并列出参数来将参数传递给程序中的main。例如:

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

这些参数将传递到mainargv

您还可以通过使用管道和重定向通过stdin发送数据来将输入传输到程序中:

SomeCommand | ./ScoreCommandLine

这将获取SomeCommand的输出,并将其用作stdin中的ScoreCommandLine流。您可以使用scanf等来阅读它。

在您的情况下,您应该重写程序,以便您不希望通过命令行传递所有参数,或者您应该使用xargs实用程序转换{{1}进入命令行参数:

stdin

希望这有帮助!

答案 1 :(得分:1)

这不会作为参数传递给程序,但它将通过管道传递到stdin程序的./ScorecommandLine - 您将能够通过scanf和类似函数读取它,但不是命令行参数。

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

在检查了您的程序后,我建议删除if (argc!=15),因为您正在使用stdin阅读scanf,而不是在任何地方解析命令行参数。

相关问题