【问题标题】:Command line arguments, reading a file命令行参数,读取文件
【发布时间】:2013-05-27 23:51:30
【问题描述】:

如果我进入命令行 C: myprogram myfile.txt

如何在我的程序中使用 myfile。我必须扫描它还是有任意访问它的方式。

我的问题是如何在我的程序中使用 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()打开它。
  • 您的问题是关于如何读取文件,还是关于如何从参数列表中获取文件名?
  • 请注意,如果您使用的是类 unix 系统,您可以以myprogram < myfile 运行您的程序,并且文件的内容将被输入到标准输入中。

标签: c file arguments command-line-arguments


【解决方案1】:

您可以使用int main(int argc, char **argv) 作为您的主要功能。

argc - 将是程序输入参数的计数。
argv - 将是指向所有输入参数的指针。

所以,如果你输入C:\myprogram myfile.txt 来运行你的程序:

  • argc 将是 2
  • argv[0] 将是 myprogram
  • argv[1] 将是 myfile.txt

更多详情can be found here

读取文件:
FILE *f = fopen(argv[1], "r"); // "r" for read

其他模式打开文件,read this

【讨论】:

  • 如何将txt文件名传递给另一个函数,而不是main
【解决方案2】:
  1. 像这样声明你的主干

    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”表示您打开文件进行阅读(更多关于其他模式here

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

    fgets (buffer_to_store_data_in , 50 , file_handle);

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

    fclose(file_handle);

全部完成:)

【讨论】:

    【解决方案3】:

    这是编程 101 方式。很多事情都是理所当然的,而且它根本不做任何错误检查!但它会让你开始。

    /* 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 */ 
    }
    

    【讨论】:

      【解决方案4】:

      命令行参数只是普通的 C 字符串。你可以对他们做任何你想做的事。在您的情况下,您可能想要打开一个文件,从中读取一些内容并关闭它。

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

      【讨论】:

        【解决方案5】:

        您收到的有关使用命令行的所有建议都是正确的,但是 在我看来,您也可以考虑使用读取 stdin 而不是文件的典型模式,然后通过管道驱动您的应用程序,例如 cat myfile &gt; yourpgm。 然后您可以使用scanf 从标准输入读取。 以类似的方式,您可以使用stdout/stderr 来生成输出。

        【讨论】:

          最近更新 更多