为什么没有任何传递给 argv[] 的参数?

Why aren't there any passed arguments to argv[]?

因此,我注意到我的 argc 始终是 1,因为我总是会收到消息 Error: missing command line arguments!,但正如代码中所述,我使用的是 argv[1]argv[2] 读取文件名。

在这种情况下,不应该自动 argc 成为 3,并且能够传递该错误吗?

备注:

  1. 如果我没有使用 if (argc < 2) 语句,输入输出文件的名称后,我的程序就会崩溃。
  2. 对于输入文件,我已经在项目文件夹中创建了这个文件,所以我只需输入该文件的名称。

这是代码:

#include <stdio.h>   
#include <stdlib.h>

FILE *IN, *OUT;

int main(int argc, char* argv[])
{
    if (argc < 2) 
    {
        printf("Error: missing command line arguments!\n");
        return 1;
    }

    printf("Enter the name of the file with the input data: ");
    scanf("%s", argv[1]);

    printf("\nEnter the name of the file for the output data: ");
    scanf("%s", argv[2]);

    IN = fopen(argv[1], "r");
    OUT = fopen(argv[2], "w");  

    fclose(IN);
    fclose(OUT);

    return 0;
}

您完全误解了 argcargv 的目的。它们应该在程序启动之前接收提供的命令行参数(程序参数),而不应该在运行时保存 scannned 输入。

引用 C11,章节 §5.1.2.2.1,

If they are declared, the parameters to the main function shall obey the following constraints:

— The value of argc shall be nonnegative.

argv[argc] shall be a null pointer.

— If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment.

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.

具体来说,当一个程序被调用时

./a.out three total arguments

那么,在你的程序中

  • argc 将是 4
  • argv[0] 将是 ./a.out
  • argv[1] 将是 three
  • argv[2] 将是 total
  • argv[3] 将是 arguments
  • argv[4] 将是 NULL(参见上面 argv[argc] 的 属性)

(一般来说,argv[1] - argv[argc-1] 将包含提供的参数,argv[argc] 将是 NULL)

您不需要明确地扫描输入,这些值将从主机环境中填充。

另一方面,您不能像

那样调用程序
./a.out

期望 argc3(或除 1 以外的任何其他值)和 argv[1] - argv[n-1]valid 因为在编译时调用程序无法知道你 plan 在运行时提供一些值.这不是千里眼。