//Checks if an argument was specified
if (argv[1] != "")
strcpy(Buff1, argv[1]);
else
strcpy(Buff1, "default");
If I run:
./program test
Buff1 = test
If I run:
./program
Buff1 = PACKAGES/=packages
How do I make it if nothing was specified, that Buff1 would be "default" by default?
Okay, if nothing is passed, argc is going to be 1 (argc gives the number of passed arguments). This means that the only argv element with anything in it will be argv[0] (which contains the name of the program). That means a call to argv[1] will be an index out of range, possibly causing a crash, or if you're lucky will just be junk data.
if(argc == 1)
strcpy(Buff1, "default");
else if(argc == 2)
strcpy(Buff1, argv[1]);
else
//do something here if there is more than 1 argument passed to it
It's also worthwhile to note that the way you passed the example arguments would not work with what you're intending: "./program test Buff1 = test" would result in argc being 4, with argv[0] being "test", argv[1] being "Buff1", argv[2] being "=" and argv[3] being "test".
Simply calling "./program test helllooo" would work with the program snipit I provided, filling Buff1 with "helllooo". And calling "./program test" would also work, filling Buff1 with "default". To do anything more advanced, you're going to have to get into command line switches (like ./program test -b somethinghere -x somethinghere), which is just a more advanced way of parsing argc and argv.
The argc gives You the number of arguments passed to the program.
Keep in mind that argc can not be less than 1 since argv[0] is always program's name so if there were no arguments passed You should use this if(argc == 1){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With