命令行参数,读取文件

18

如果我在命令行中输入了以下命令:

C: myprogram myfile.txt

我该如何在程序中使用myfile呢?是否需要使用scanf读取它,还是有其他任意访问的方法?

我的问题是如何在程序中使用myfile.txt文件。

int
main(){
    /* So in this area how do I access the myfile.txt 
    to then be able to read from it./*

你可以使用 fopen()open() 打开它。 - Barmar
你的问题是关于如何读取文件,还是关于如何从参数列表中获取文件名? - Barmar
1
请注意,如果您使用类Unix系统,则可以将程序运行为myprogram < myfile,文件的内容将被输入到stdin中。 - John Carter
5个回答

24
您可以使用int main(int argc, char **argv)作为主函数。 argc - 是您的程序输入参数的数量。
argv - 是指向所有输入参数的指针。
如果您输入C:\myprogram myfile.txt来运行您的程序:
  • argc将是2
  • argv[0]将是myprogram
  • argv[1]将是myfile.txt
更多细节,请查看此处
要读取文件:
FILE *f = fopen(argv[1], "r"); // "r"用于读取 如需以其他模式打开文件,请阅读此文档

如何将 txt 文件名传递给另一个函数,而不是传递给 main 函数? - Sigur

4
  1. 声明main函数如下:

    int main(int argc, char* argv [])

    • argc指定参数的数量(如果没有传递参数,则对于程序名称,它等于1)

    • argv是一个指向字符串数组的指针(至少包含一个成员 - 程序名称)

    • 您可以像这样从命令行读取文件:C:\my_program input_file.txt

  2. 设置文件句柄:

    File* file_handle;

  3. 打开file_handle以便读取:

    file_handle = fopen(argv[1], "r");

    • fopen返回一个指向文件的指针,如果文件不存在则返回NULL。 argv1包含要作为参数读取的文件

    • "r"表示您打开该文件以进行读取(关于其他模式的更多信息请查看此处

  4. 使用例如fgets读取内容:

    fgets(buffer_to_store_data_in, 50, file_handle);

    • 您需要一个char *缓冲区来存储数据(例如字符数组),第二个参数指定要读取多少,第三个参数是文件的指针
  5. 最后关闭句柄

    fclose(file_handle);

完成啦 :)


3

这是编程入门的方法。它假设了很多内容,并且没有进行任何错误检查!但它可以帮助你开始。

/* this has declarations for fopen(), printf(), etc. */
#include <stdio.h>

/* Arbitrary, just to set the size of the buffer (see below).
   Can be bigger or smaller */
#define BUFSIZE 1000

int main(int argc, char *argv[])
{
    /* the first command-line parameter is in argv[1] 
       (arg[0] is the name of the program) */
    FILE *fp = fopen(argv[1], "r"); /* "r" = open for reading */

    char buff[BUFSIZE]; /* a buffer to hold what you read in */

    /* read in one line, up to BUFSIZE-1 in length */
    while(fgets(buff, BUFSIZE - 1, fp) != NULL) 
    {
        /* buff has one line of the file, do with it what you will... */

        printf ("%s\n", buff); /* ...such as show it on the screen */
    }
    fclose(fp);  /* close the file */ 
}

0

命令行参数只是普通的C字符串。您可以随心所欲地使用它们。在您的情况下,您可能想打开一个文件,从中读取一些内容,然后关闭它。

您可能会发现这个问题(和答案)很有用。


0
所有关于使用命令行的建议都是正确的,但是我觉得你也可以考虑使用一种通用的模式,即读取stdin而不是文件,然后通过管道驱动你的应用程序,例如 cat myfile > yourpgm。 然后你可以使用scanf从标准输入中读取数据。 类似地,你可以使用stdout/stderr来产生输出。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接