简体   繁体   中英

Add a command to a C program in Linux

I'm new to C and Linux. When run a compiled program in terminal, like:

./myProg --myCommand1

then myProg will do the job according to the command "myCommand1". I'd like add several commands to the myProg. I'm not sure if char *argv[] can be used for this.

Thanks.

检查GNU getopt ,以获取解析cmdline参数的简便方法

It can be used. argv[1] is the first command, argv[2] is the second, etc.

Yes, you need to use your argc and argv arguments precisely for this. http://www.cprogramming.com/tutorial/c/lesson14.html has a small tutorial on using them.

Most Linux command line programs parse their arguments with a C level routine called getopt() . It has some advantages to just walking the argv[] array, basically it will handle argument rearrangements, short and long flags, help messages, usage statements, and a number of items that are now generally taken for granted in a well working command line program. I highly suggest you take a day or more to learn about it.

While it is easy to add an argument to an getopt using program, writing the code that does something if the argument is set could be very easy, or very very hard, depending on what you envision doing, how well your vision is detailed, and how suitable your details are to being implemented by a computer program.

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