【问题标题】:C - pass an input and an output text file through command line to my programC - 通过命令行将输入和输出文本文件传递给我的程序
【发布时间】:2018-12-20 04:02:55
【问题描述】:

我需要以命令行形式通过我的程序传递两个文件

./your_executable inputfile.txt outputfile.txt

在我的示例中,我使用的是

gcc coursework.c CircleCode.txt CircleCode_tmp.txt

因此第二个文件不存在并在程序中打开。

int main(int argc, char **argv[])
{
    FILE *orginalFile = fopen(*argv[1], "r");
    FILE *newFile = fopen(*argv[2], "w");

    if (orginalFile == NULL || newFile == NULL)
    {
        printf("Cannot open file");
        exit(0);
    }
}

Clang 中的错误:

error: no such file or directory: 'CircleCode_tmp.txt'

【问题讨论】:

  • 您对参数argv的声明不正确。您可以使用char **argv,也可以使用char *argv[];这些是等价的。另一方面,您的 char **argv[] 意味着不同的东西,它与实际参数不匹配。更正声明后,还要更正用途,每个用途都应该少一个间接级别。
  • 您还应该在使用argv[1]argv[2] 之前检查if (argc < 3) { fputs ("error: insufficient input.\n", stderr); return 1; }。如果没有传递任何参数,argv[1] 将是 NULLargv[2] 一个不确定的地址。
  • 呃...您正在将这些文件名传递给您的编译器。当您运行程序时,您希望它们作为程序本身的命令行参数。
  • 你需要编译和运行两个不同的步骤。用 gcc -Wall coursework.c -o coursework 编译用 ./coursework CircleCode.txt CircleCode_tmp.txt 当然你还需要修复其他提到的问题厘米。

标签: c file-handling


【解决方案1】:

main()的签名不对。

可以改成

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

int main(int argc, char **argv)                                        

因为argv 是指向一个字符串数组。

this post


由于您的程序需要输入和输出文件才能工作,因此您应该检查是否收到了所需数量的参数。

argc 将有参数的数量。由于用于运行程序本身的命令名称与两个文件一起算作参数,因此程序至少需要 3 个参数。

所以你可以做类似的事情

if(argc<3)
{                                                                        
   perror("Not enough arguments.");                                       
   return 1;                                                              
} 

还有

gcc coursework.c CircleCode.txt CircleCode_tmp.txt  

您要求编译器同时编译您的输入和输出文本文件,这可能不是您想要的。

相反,你可以这样做

gcc -Wall coursework.c -o your_executable

编译程序然后运行它

./your_executable CircleCode.txt CircleCode_tmp.txt

gcc-Wall 选项用于启用一些警告,这些警告可以更好地帮助您发现和纠正错误。

参见this 讨论。

【讨论】:

    【解决方案2】:

    argv类型为char**,不需要[]

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char** argv) {
        FILE* orginalFile = fopen(argv[1], "r");
        FILE* newFile = fopen(argv[2], "w");
    
        if (orginalFile == NULL || newFile == NULL) {
          printf("Cannot open file");
          exit(0);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-17
      • 2019-04-19
      • 2016-06-20
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      相关资源
      最近更新 更多