如何使用从C中的命令行作为参数传入的文本文件?

时间:2014-02-28 00:12:38

标签: c buffer command-line-arguments fgets

我正在努力弄清楚如何使用作为命令行参数传入的文本文件。我根本不知道将文件文本放入我的程序中使用。我的代码看起来像这样....

    char buffer[80];
    int i;
    int lineCount = 0;

    fgets(buffer, 80, stdin);  //get the first line

    while (buffer != NULL) {  
        // do some stuff
    }//end fgets while

这是一项家庭作业,我知道我的老师将使用以下命令运行该程序:

    username@mylunixbox$ ./a.out <data1> output1

data1是我尝试使用的文本文件。

2 个答案:

答案 0 :(得分:1)

使用argv [1]。这将为您提供文件名,然后您可以使用fopen()并使用文件操作从文件中读取内容。

答案 1 :(得分:0)

int main(int argc, char **argv)
{
    int rc = EXIT_SUCCESS;
    for (int i = 1; i < argc; i++)
    {
        FILE *fp = fopen(argv[i], "r");
        if (fp == 0)
        {
            fprintf(stderr, "%s: failed to open file %s for reading\n",
                    argv[0], argv[i]);
            rc = EXIT_FAILURE;
        }
        else
        {
            char line[4096];
            while (fgets(line, sizeof(line), fp) != 0)
                ...do stuff with the line read from the file...
            fclose(fp);
        }
    }
    return rc;
}