C 命令行参数:需要澄清参数输入的顺序和一般的命令行参数

C Commandline Arguments: Need Clarification About Order of Arguments Input And Commandline Arguments In General

这是书中的示例代码。该程序打印给定的字符串以重复给定的次数。

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

void usage(char *program_name)
{
    printf("Usage: %s <nessage> <# of times to repeat>\n", program_name);
    exit(1);
}

int main(int argc, char *argv[]) {
    int i, count;

    if(argc < 3)
        usage(argv[0]);

    count = atoi(argv[2]);
    printf("Repeating %d times..\n", count);

    for(i=0; i < count; i++)
       printf("%3d - %s\n", i, argv[1]);
}

它做了它应该做的事情:

kingvon@KingVon:~/Desktop/asm$ ./convert 'Whosebug is the best place to ask questions about programming' 6
Repeating 6 times..
  0 - Whosebug is the best place to ask questions about programming
  1 - Whosebug is the best place to ask questions about programming
  2 - Whosebug is the best place to ask questions about programming
  3 - Whosebug is the best place to ask questions about programming
  4 - Whosebug is the best place to ask questions about programming
  5 - Whosebug is the best place to ask questions about programming
kingvon@KingVon:~/Desktop/asm$ 

问。现在虽然 main 按照这个特定的顺序接受两个参数:(int argc, char *argv[]),为什么当我 ./convert 'string' (number) 它工作正常但其他方式围绕 `./convert (number) 'string'不起作用?

kingvon@KingVon:~/Desktop/asm$ ./convert 5 'Whosebug is the best place to ask questions about programming'
Repeating 0 times..

问。这条线 if(argc < 3) usage(argv[0]); 我有 2 个问题: 这一行指定如果给定的整数参数小于 3,程序应该输出用法。 ./convert 'string' 2 不打印用法?那么这里发生了什么? usage 也将 char *program_name 作为参数(char *program_name 是什么意思?)但是在上面的行中给出了 argv[0] 作为参数。这是为什么,它有什么作用?

argc 变量是 argv 数组中元素的数量。实际的命令行参数将在 argv 数组中。

命令行中的第一个参数总是在 argv[1],第二个在 argv[2],等等

如果你在 运行 程序中改变了顺序,程序不知道这一点,并且会认为要打印的字符串仍然在 argv[1] 中,而数字在 argv[2]。如果不是这样,程序将无法正常工作。

argc 检查仅检查参数的 数量 ,而不检查它们的顺序。


程序名称(您问题中的 "./convert" )始终作为参数零传递,即在 argv[0].

argc 是命令行上参数的数量,而不是任何特定参数的值。 argv 包含作为字符串传递的实际参数。 argv[0] 是用于调用程序的命令,argv[1] 是第一个参数,依此类推

当您将程序调用为

./convert 'Whosebug ...' 6

然后

argv[0] == "./convert"
argv[1] == "Whosebug ..."
argv[2] == "6”
argc == 3

代码假定数字在 argv[2] 中传递并使用 atoi 函数将其从整数的字符串表示形式转换为整数值,这就是代码没有的原因'当您切换参数的顺序时,它的行为与预期一致。如果您希望能够调换参数的顺序,那么您的代码必须知道如何检测哪个参数是哪个。