C語言--在命令列輸入檔案名稱字並列印檔案內容

來源:互聯網
上載者:User

標籤:c   c語言   讀取檔案   argc   argv   

C語言編程中,經常遇到main函數中argc和argv[]這兩個參數。argc是argument count的縮寫,即參數的個數;argv是argument vector的縮寫,即參數列表。argv[0]是程式本身的名字,argv[1]是在命令列中輸入的第一個程式的參數,argv[argc]是NULL,如下所示:

#include "stdio.h"int main (int argc, char *argv[]){    printf ("the argc value is %d \n", argc);    int i;    for (i = 0; i <= argc; i++){            printf ("the argv[%d] value is %s \n", i, argv[i]);    }    return 0;}#將上述代碼編譯為test可執行檔,在命令列輸入如下內容/*./test arg_1 arg_2*/#執行結果如下:/*the argc value is 3 the argv[0] value is ./test_c_0 the argv[1] value is arg_1 the argv[2] value is arg_2 the argv[3] value is (null)*/

搞清楚了argc和argv[],我們就可以使用兩者通過命令列向程式傳送將要處理的檔案名稱參數,代碼如下。

#include "stdio.h"int main (int argc, char *argv[]){    FILE *fp;    int c;    fp = fopen( argv[1], "r");    while ( (c = fgetc(fp)) != EOF){        printf ("%c", c);    }    fclose(fp);    return 0;}



C語言--在命令列輸入檔案名稱字並列印檔案內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.