简体   繁体   中英

main(int argc, char *argv[]) giving strange results for * as command line argument

 #include <stdio.h>

int main(int argc, char *argv[])
{
    printf("%d\n", argc);
}

This simple program compiled with gcc

saad@saad-700Z3C-700Z5C:~/KANDR$ ./a.out 
1
saad@saad-700Z3C-700Z5C:~/KANDR$ ./a.out 13 432
3
saad@saad-700Z3C-700Z5C:~/KANDR$ ./a.out 13 432 + 
4
saad@saad-700Z3C-700Z5C:~/KANDR$ ./a.out 13 432 +  *
112
saad@saad-700Z3C-700Z5C:~/KANDR$ ^C

Why does the last command return 112, when i have * as command line argument?

Because the shell expands the * to the file names in the current directory. To make sure try like this

for (size_t i = 0 ; i < argc ; ++i)
    fprintf(stdout, "arg[%zu]: %s\n", i, argv[i]);

It's exactly how rm * would remove all files in the current directory.

The * in shell extract all the files in the current directory and put into the command line arguments list. So the argc coming 112. If you want to pass the "*" to the program you can use the below methods.

"*" (or) '*' (or) \\*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM