2013-02-07 34 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,而不是在任何地方解析命令行參數。