C语言 C 中 main 的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4176326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:03:15  来源:igfitidea点击:

Arguments to main in C

ccommand-line-argumentsmain-method

提问by Anthony

I don't know what to do! I have a great understanding of C basics. Structures, file IO, strings, etc. Everything but CLA. For some reason I cant grasp the concept. Any suggestions, help, or advice. PS I am a linux user

我不知道该怎么办!我对 C 基础知识有很好的理解。结构、文件 IO、字符串等。除了 CLA 之外的一切。出于某种原因,我无法理解这个概念。任何建议、帮助或建议。PS我是Linux用户

回答by cdhowie

The signature of mainis:

的签名main是:

int main(int argc, char **argv);

argcrefers to the number of command line arguments passed in, which includesthe actual name of the program, as invoked by the user. argvcontains the actual arguments, starting with index 1. Index 0 is the program name.

argc指传入的命令行参数的数量,其中包括用户调用的程序的实际名称。 argv包含实际参数,从索引 1 开始。索引 0 是程序名称。

So, if you ran your program like this:

所以,如果你像这样运行你的程序:

./program hello world

Then:

然后:

  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".
  • argc 将是 3。
  • argv[0] 将是“./program”。
  • argv[1] 将是“你好”。
  • argv[2] 将是“世界”。

回答by Toby

For parsing command line arguments on posix systems, the standard is to use the getopt()family of library routines to handle command line arguments.

对于在 posix 系统上解析命令行参数,标准是使用getopt()库例程系列来处理命令行参数。

A good reference is the GNU getopt manual

一个很好的参考是GNU getopt 手册

回答by Siamore

Imagine it this way

想象一下

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

也许一个示例程序会有所帮助。

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

    printf("you entered in reverse order:\n");

    while(argc--)
    {
        printf("%s\n",argv[argc]);
    }

return 0;
}

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

它只是以相反的顺序打印您作为参数输入的所有内容,但您应该制作一些更有用的新程序。

compile it (as say hello) run it from the terminal with the arguments like

编译它(比如你好)从终端运行它,参数如下

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

然后尝试修改它,以便它尝试检查两个字符串是否彼此相反,然后您将需要检查 argc 参数是否正好为 3 如果还有其他内容会打印错误

if(argc!=3)/*3 because even the executables name string is on argc*/
{
    printf("unexpected number of arguments\n");
    return -1;
}

then check if argv[2] is the reverse of argv[1] and print the result

然后检查 argv[2] 是否与 argv[1] 相反并打印结果

./hello asdf fdsa

should output

应该输出

they are exact reverses of each other

the best example is a file copy program try it it's like cp

最好的例子是一个文件复制程序试试它就像 cp

cp file1 file2

cp文件1文件2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

cp 是第一个参数(argv[0] 不是 argv[1]),大多数情况下你应该忽略第一个参数,除非你需要引用或其他东西

if you made the cp program you understood the main args really...

如果你编写了 cp 程序,你就真正理解了主要的参数......

回答by anthony

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

Siamore,我一直看到每个人都使用命令行来编译程序。我通过 code::blocks 从 ide 使用 x11 终端,这是我的 linux 机器上的 gnu gcc 编译器。我从来没有从命令行编译过程序。所以 Siamore,如果我希望程序名称是 cp,我是否初始化 argv[0]="cp"; Cp 是一个字符串文字。命令行上有任何要输出到标准输出的东西???你给我的Siamore的例子我明白了!输入的字符串虽然有几个字,但也只有一个arg。因为它包含在双引号中。所以 arg[0],prog 名称,实际上是带有换行符的字符串文字??所以我明白你为什么使用 if(argc!=3) 打印错误。因为 prog name = argv[0] 之后还有 2 个 args,并且再次发生错误。我还有什么理由使用它?我真的认为我对如何从命令行或终端编译缺乏了解是我对这方面缺乏了解的原因!!Siamore,你帮助我更好地理解了 cla!仍然不完全理解,但我并没有忘记这个概念。我将学习从终端编译,然后重新阅读您写的内容。我敢打赌,到时候我就完全明白了!在你的帮助下,哈哈

<> Code that I have not written myself, but from my book.

<> 不是我自己写的代码,而是我的书。

#include <stdio.h>

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

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

这是输出:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

所以 argv 是一个字符串文字表, argc 是它们的数量。现在 argv[0] 是程序的名称。所以如果我输入 ./CLA 来运行程序 ./CLA 是 argv[0]。上面的程序将命令行设置为接受无限数量的参数。如果我愿意,我可以将它们设置为仅使用 3 或 4 个。就像一个或你的例子所示,Siamore... if(argc!=3) printf("这里出现一些错误"); 谢谢Siamore,没有你就做不到!也感谢帖子的其余部分付出的时间和精力!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

PS,以防将来出现这样的问题......你永远不会知道问题是因为我使用的是IDE AKA Code::Blocks。如果我在上面运行该程序,它将打印该程序的路径/目录。示例: ~/Documents/C/CLA.c 它必须从终端运行并使用命令行编译。gcc -o CLA main.c 并且您必须在该文件的目录中。

回答by Yusuf Khan

Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.

main 和其他函数一样,argc 和 argv 和其他函数参数一样,区别在于 main 是从 C Runtime 调用的,并将参数传递给 main,但 C Runtime 是在 c 库中定义的,你不能修改它, 因此,如果我们确实在 shell 上或通过某些 IDE 执行程序,我们需要一种机制将参数传递给 main 函数,以便您的 main 函数可以根据您的参数在运行时表现不同。参数是 argc ,它给出了参数的数量, argv 是指向指针数组的指针,它将值保存为字符串,这样你就可以传递任意数量的参数而不限制它,这是实现 var args 的另一种方式。

回答by Nebojsa Tomcic

Had made just a small change to @anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:

对@anthony 代码做了一个小改动,这样我们就可以得到带有参数数字和值的格式良好的输出。当您有多个参数时,以某种方式更容易阅读输出:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("The following arguments were passed to main():\n");
    printf("argnum \t value \n");
    for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
    printf("\n");

    return 0;
} 

And output is similar to:

输出类似于:

The following arguments were passed to main():
0        D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1        -P
2        TestHostAttoshiba
3        _http._tcp
4        local
5        80
6        MyNewArgument
7        200.124.211.235
8        type=NewHost
9        test=yes
10       result=output