2012-09-18 53 views
1

你好我有一個項目,我正在做的,我需要我的程序從命令行運行,並能夠讀取將在程序中使用的標誌和文件名。讀取標誌和文件名C中的命令行參數

這是我現在的代碼。它編譯時不輸入任何標誌。我不認爲我的GetArgs做任何事情。我曾幫助過這部分代碼。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAX 1024 
#define IN 1 /* inside a word */ 
#define OUT 0 /* outside a word */ 
/* count lines, words, and characters in input */ 

int numInputArgs; 
int idx; 
void GetArgs (int argc, char **argv){ 

for (idx = 1; idx < 4; idx++) { 
    if (strcmp(argv[idx], "-c") == 0) { 
     printf("Flag -c passed\n"); 
     break; 
    } 
    else if (strcmp(argv[idx], "-w") == 0) { 
     printf("Flag -w passed\n"); 
     break; 
    } 
    else if (strcmp(argv[idx], "-l") == 0) { 
     printf("Flag -l passed\n"); 
     break; 
    } 
    else if (strcmp(argv[idx], "-L") == 0) { 
     printf("Flag -L passed\n"); 
     break; 
    } 
    else { 
     printf("Error: unknown flag\n"); 
     exit(-1); 
    } 
} 
}// end GetArgs 

void lineWordCount () { 

int c, nl, nw, nc, state; 


    state = OUT; nl = nw = nc = 0; 
    while ((c = getchar()) != EOF) { 
      ++nc; 

     if (c == '\n') 
      ++nl; 

     if (c == ' ' || c == '\n' || c == '\t') 
      state = OUT; 

     else if (state == OUT) { 
      state = IN; ++nw; 
     } 
     printf("%d %d %d\n", nl, nw, nc); 
    } 
}// end lineWordCount 








int main(int argc, char **argv){ 

GetArgs(argc, argv); 
lineWordCount(); 
printf("Hello"); 

//fclose(src); 
} 
+0

僅供參考:家庭作業標籤已棄用。 – nneonneo

+0

我不明白。 –

+0

你說得對,所有'GetArgs'都會打印參數。如果你在POSIX機器上(比如Linux或Mac OSX),我建議你看看['getopt'](http://pubs.opengroup.org/onlinepubs/009695399/functions/getopt.html)。如果你搜索的話,還有許多解析庫可用的參數,上面提到的'getopt'函數也適用於Windows。 –

回答

3

您可以使用一個標準的功能像getopt()由@Joachim提到,如果您的系統上,或者你也可以自己編寫它。如果你有一個複雜的命令行語法,getopt()可能更適合 - 如果你只需要檢查一組有限的標誌,它可能更容易自行編碼它,例如:

void GetArgs (int argc, char **argv){ 
    int idx = 0; 

    for (idx = 1; idx < argc; idx++) { 
     if (strcmp(argv[idx], "-a") == 0) { 
      printf("Flag -a passed\n"); 
     } else if (strcmp(argv[idx], "-b") == 0) { 
      printf("Flag -b passed\n"); 
     } else if (strcmp(argv[idx], "-c") == 0) { 
      printf("Flag -c passed\n"); 
     } else { 
      printf("Error: unknown flag %s\n"); 
     } 
    } 
} 
+0

我的main有什麼問題..除了lineWordCount –

+0

之外,它沒有打印任何其他內容lineWordCount()在上面的代碼中沒有被調用。我把你的代碼,並將其傳遞給編譯器未經修改,當我用幾個命令行參數調用它的程序,它打印每一個,正是我所期望的... –

+0

我添加它在正確的GetArgs在主,我是陷入GetArgs中。試圖弄亂它,所以它會得到lineWordCount。我現在就更新代碼。 –

0

我建議你使用argtable2庫。我已經使用了很長時間,我認爲它很棒。有教程可以看到它是多麼強大和易於使用。