简体   繁体   中英

Is it possible to use <unistd.h> and <getopt.h> in c to read an argument with white spaces between words?

I'm kinda new to C and programming, so take this with a grain of salt. Basically, I'm trying to have the getopt function to receive arguments with white spaces between them. For example :

./covid19 -i f_texto1.csv -L all -S inf 2020-27 -D inf -P max 5000 -o f_dados.dat

In here, when I want to put -S I need to say inf and a week of 2020, but I can only get it to take the "inf" part.

If you provide the arguments with spaces in them, getopt() and friends will return those arguments with spaces in them. You have to tell the shell to preserve the spaces — usually by using quotes, though you can use backslashes if you prefer.

For instance:

./program one 'two potatoes' 'three   spaces' "  spaces before and after  " \ \ seven\ backslashes\ \\\ vanish\ \ 

Standard Unix shells will treat that so that inside the program, the int main(int argc, char **argv) function sees:

argc    = 6;
argv[0] = "./program";
argv[1] = "one";
argv[2] = "two potatoes";
argv[3] = "three   spaces";
argv[4] = "  spaces before and after  ";
argv[5] = "  seven backslashes \\ vanish  "; // Note there's a single backslash left
argv[6] = NULL;

Granted, there are no -x type options in that, but you could add them as you wish. The value in optarg will contain spaces when the corresponding argument (or part of an argument) contains spaces.

It is important to understand the interaction between your shell and the programs it executes.

You would need to type your command line as:

./covid19 -i f_texto1.csv -L all -S "inf 2020-27" -D inf -P "max 5000" -o f_dados.dat

With GNU getopt() , assuming the option string includes "i:L:S:D:P:o:", and without export POSIXLY_CORRECT=1 , you would get the 2020-27 and 5000 as positional arguments after the options -i , -L , -S , -D , -P and -o had been processed in the main while ((opt = getopt(argc, argv, "i:L:S:D:P:o:")) != -1) { … } loop.

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