简体   繁体   中英

How to modify/use command line argument in main function if it is a string?

I want to compare the different elements of a command-line argument. It would be entered all together resulting in the string being found at argv[1] . However, I am not sure how to compare the elements and individual characters as I am looking for repetitions.

If I compared [2] to [3] in the string, there would be nothing there as only 1 string is entered in the command line argument and I need to compare the characters found within that string argv[1] . I am unable to include spaces so I wouldn't be able to compare argv[2] to argv[1] .

Read Modern C and see this C reference .

If you code for Linux, read also documentation of GNU libc , in particular the section on parsing program arguments .

You could also use strcmp(3) to compare your program argument to some fixed constant string.

The program arguments are given to your main function, traditionally defined as int main(int argc, char**argv) . They are always strings (of different addresses), and on POSIX you are practically certain that argc>0 , argv[0] is a non-empty string (somehow the name of the program), all argv[i] with i >= 0 and i < argc are non-null, and argv[argc] is NULL .

You could code inside your main something like

 if (argc>1 && !strcmp(argv[1], "foo")) {
    /// handle `foo` as first program argument
 }

I would recommend to study for inspiration the source code of GNU findutils or of GNU make .

I don't recommend modifying program arguments with eg some code like strcpy(argv[1], "bar") . It is not portable, perhaps forbidden, and certainly unreadable and brittle.

If you are on Linux, see also proc(5) about /proc/self/cmdline

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