How to capture parameters after some string in commandline? - c

How to capture a parameter after some string in command line?
./executable.out -apps path_to_out
In the above code I want to store path_to_out in a string variable. What is the efficient way of doing that?

It kind of depends what kind of options you want. If you are willing to have only single-letter options, you can use the C library function getopt to parse the command line. If you would like long options (e.g., --apps), you can use getopt_long, but this is a GNU extension that will not port well. If you want really, really fancy option parsing, you can use something like GLib.
Of course, you can just roll your own, iterating over the arguments from 1 to argc and, when you encounter -apps, check that i+1 < argc and grab the next argument.

argv[argc-1] already has the value for you if your path is the last argument in the command line.
if your main is like :
int main(int argc,char **argv)
all the command line arguments are in char **argv.
in your case:
argv[2] is path_to_out.
if you want to copy it in a string,you can anyhow do this below thing:
string path(argv[2]);

It appears that by asking "after some string on the commandline" you are referring to the fact that the commandline argument -apps started with a dash, which makes it an "option".
The preferred way to doing this is to use a predefined library for processing options, such as getopt on GNU systems.

when you run parameter store in this way..
Example:---> ./executable.out -apps path_to_out
argv[0] will be "./executable.out"
argv[1] will be "-apps"
and argv[2] will be "path_to_out".

Related

Parsing double-character command using getopt() C

Is there a way to make getopt() or getopt_long() recognise double character option?
example: ./a.out -my argument where my is single command.
You can use getopt_long_only, which will try to process options as long ones even if there is only one - sign before them.
This function is GNU extension, as well as getopt_long.

Command line arguments without the hyphen

How can I parse arguments without the hyphen in C?
I.e. virsh install vm
or
git pull origin master
When I tried it out, if there is no - prefix, everything just gets ignored and argc returns 1 (argv[0] is the program call).
I'm using Linux, but it would be nice if there was a cross platform method to achieve this.
UPDATE: the problem was me using a # in front of the first argument, I was trying to pass in #XX eg number_program #12. Needless to say this doesn't work.
Are you using some library to parse the arguments for you? There is no special 'hyphen' arguments when passing in parameters to a C program specifically. Parse argv however you like.
For example:
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
for(i=0; i<argc; i++) {
//dont do this without proper input validation
printf("%s\n", argv[i]);
}
return 0;
}
Example run:
$ ./a.out test test test -hyphen
./a.out
test
test
test
-hyphen
argv contains the program name and the arguments to the program, in the order they were given in the command line.* Hyphens aren't special; they just make it easy for both people and computers to separate options from other args.
If you want to interpret args a certain way, that's your prerogative. That's what git does, basically interpreting argv[1] (if it exists, of course) as the name of a subcommand. And you don't need any libraries in order to do that. You just need to decide how you want the args interpreted.
* Modulo some cross-platform differences in how args are parsed; *nix typically does some pre-parsing for you and expands wildcard patterns, for example. You won't have 100% cross-platform compatibility unless you understand those differences and are ready for them.

Execv for own terminal

I am currently writing my own terminal in C.
I found out, that there is multiple variants of the exec() methode, that i can use.
Its simple occurance lead me to use execv():
int main(int argc , char* argv[]){
char* dir = getcwd(NULL, 0);
char* command[] = {"echo", "Hello", "World", "!!!", NULL};
execv(dir, command);
}
From my understanding this should work. It is compiling, but nothing happens.
The path argument to execv is supposed to be the path specification to the executable file you want to run, not just a directory as returned by getcwd. From the manpage:
The initial argument for these functions is the pathname of a file which is to be executed.
In other words, you're looking for something like:
execv ("/bin/echo", command);
The code you currently have is trying to run your current directory, something that's unlikely to end well, and something you may have noticed if you checked the return value from execv along with errno: nudge, nudge, wink, wink :-)
In terms of what to do for other programs, you simply substitute their full path name for /bin/echo.
You should also be aware that exec is a family of functions, each with slight variations.
Some allow environments to be passed, some automatically search the path for your executable (depending on the name given), and some use variable argument lists rather than arrays. If you want to use the automatic path searching, you would look into execvp rather than execv, then you don't have to worry about where the executable file is located.

How to use getopt when option is a string on C?

I'm working/developing a C program for my university, that can have 3 options when invoked (-h for help, -o <argument> (with or without it) and last option can be a string like(test-in-1):
./myprogram test-in-1
I have to process these options on my main, and do what's required when they are invoked. None of them are mandatory.
I was thinking in using getopt to parse the options however one of these options is actually a string(char *) and is with this one that I'm kinda lost since getopt is not able to read strings, only char or a char with an argument(for example,-h, -o <argument>, as far as I understood). Any idea of how can I do this?
I can't really post any code besides main line,since I'm at stuck at start of it (int main(int argc, char *argv[])).
Thanks in advance for any advice/point in right direction.
You can pass a colon : which means it requires an argument and that argument will be set in optarg.
See also my answer here
If you're linking to the GNU C library, check out getopt_long.

Distinguish between optional arguments, pathname or file? c language

I am very new with c and less experienced with any other language :/
For an assignment at uni, I am a little stuck on this small part. Essentially I am required to write a 'ls' function that has 4 optional arguments, for example:
list [-l] [-f] [pathname] [localfile]
Now, the first two are straight forward. To make things more difficult, the 'localfile' doesn't necessarily exist and the 'pathname'(if given) will be located on the server I'm connecting to through a socket (so checking if it is a file is out and checking the pathname is out). I was thinking, check last 4 chars in the string for a '.txt' or something similar. I'm actually completely stumped and will present this problem to my course conveyor tomorrow, if I can't find a solution.
This is a very small part of what I actually have to do but any push in the right direction would be appreciated.
You will need to process argc and argv to get your command line arguments. That is the first thing to work on, getting the arguments - ensuring they are correct, and determining what is being asked for.
int main(int argc, char *argv[])
Assuming your are on Linux/Unix, you will need to use the directory functions opendir()/readdir()/closedir() - dirent.h. The stat() function will be required to satisfy the -l requirement. access() will determine if a file exists and then stat() will tell you if the file is a regular file or a directory.
I'd make a struct to hold the four optional arguments and return it from a function called "process_arguments" that takes argc and argv as parameters.
struct args {
bool valid;
bool l_option;
bool f_option
char directory[200];
char filename[200];
}
With the requirement for a socket connection you will have to write a "server program" that will be constantly running on the server and a "client program" that it will fork to handle the requests from your local program. Try and locate examples of socket programs.
Another check for whether you have a path string or a filename is to look for the path separator character - '/' if the server is Unix/Linux. This scheme shouldn't have any path separators in filenames, so the presence of one tells you it is a path.

Resources