cs 288 command line arguments & env vars

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/30

encourage image

There's no tags or description

Looks like no tags are added yet.

31 Terms

1
New cards

in command line description, what do the brackets indicate:

myprogram [-f filename] input.txt


it indicates that the -f option is optional

2
New cards

what must you include to use getopt()

#include <unistd.h>

3
New cards

what does argc count?

it counts number of command line arguments. IT IS AT LEAST 1 because it also counts the program name.

4
New cards

what is argv? what does argv[0] hold?

argv is a pointer to pointer, as it holds the command line arguments as strings.

argv[0] holds the program name.

all strings in argv end with null terminator character \0

5
New cards

differentiate the following

char **argv
// and
char *argv[]


they are identical

6
New cards

what is the format of using getopt() ?

getopt(int argc, char *const argv[], const char *optstring)

pass argc and argv normally into this.

opstring is the string that tells you what options you’re looking for or if they have option arguments, such as “bla:”

7
New cards

what does a getopt call return and how are the command line argumentes processed?

each call returns one option (NOT option argument) in the order that they appear as command line arguments. it returns the option as its ASCII value.

if all options are exhausted, -1 is returned.

if an option is unknown or missing an option argument WITHOUT : at optstring start: ?

if option argument is missing and first char in opstring is : : :

8
New cards

how to accept option arguments

in the optstring, put a : after the option desired. so if you desire f, put:

"meof:w"


9
New cards

does getopt see long options, i.e. double hyphens --all

not normally no, it stops scanning.

unless you do getopt_long()

10
New cards

what is the getopt parsing while loop look like:

int opt;
while ( ( opt=getopt(argc,argv,":if:lr") )!=-1) {

	switch(opt) {
		case 'i': 
		...
		
	}
}


11
New cards

how do we handle/deal with missing option arguments if we wanna deal with them separately? and what’s the difference

normally for missing optarg, getopt returns ? . however, if we put a : at the start of the opstring, getopt returns : for missing optargs.

12
New cards

what is optarg and usage

it stores the value of an option argument if an option has one (pointer optarg points to that option argument string")


usage:

case 'f': 
	printf("%s", optarg); // print the option argument


13
New cards

what is optopt and usage

it stores the value of an unknown option or invalid option when getopt() encounters one and returns ?

usage:

case 'f':
	printf("%c", optopt);


14
New cards

what is optind and usage

option index. it starts at 1 when program starts bc of program name. it increments for everything getopt() consumes, so

./prog -a -b -c file.txt

makes getopt go from 1→2→3→4 . (file.txt is not consumed, so it doesn’t go to 5)


usage: it lets us print the operand (which is remaining command line argumnets)

for (; optind < argc; optind++){

	printf("operand: %s", argv[optind]);

}


15
New cards

what is opterr and usage

by default, opterr = 1 and getopt() prints error messages such as when an unknown option is parsed. doing opterr = 0 disables that if you don’t want error messages and want to deal with the cases yourself.

16
New cards

does getopt() support grouped option, like -a -b -c as -abc ?

yes, except when one of them requires an option. then it breaks apart. for example, “ab:c” optstring paired with CLA ./prog -abc will accept c as b's option argument.

17
New cards

what happens in getopt() when a random item not hyphenated (non option) just roams about? as in:

./a.out -n 6 -12 -f 

for optstring “:i:l:f:n”

“6” is skipped so, getopt returns in order: n ? ? : -1

where 6 is actually just left as the final thing in argv, as argv[4]. (argv[3] is the final “-f”)

18
New cards

what’s going on here?:

// optstring
getopt(argc, argv, ":if:lr");

// command line
./arg -i 'hi there' -f -q


‘hi there’ is skipped and put out as argv[5]. -q is taken in as -f's option argument since it requires one.


IMPORTANT: even if it is a valid option, if a prior option requires an optarg but doesn’t have one, it will eat the next valid OR invalid option as its optarg if one exists.

19
New cards

how to use list of environment vars in your program?

add them in main:

int main(int argc, char* argv[], char * envp[])

where envp[] holds ALL environment variables; it is a set of pointers each of which points to a string.

20
New cards

how does envp array terminate? (how do we know it ends)?

the last pointer in envp[] is a nullptr.

21
New cards

how do we iterate through all env variables using a while loop?

doing while(envp[index]) since that while loop goes on until it hits NULL

22
New cards

what does library fucntion getenv() do and return?

doing getenv(“NAME”) returns the value of what the environment variable NAME stores.

for example, doing getenv(“SHELL”) returns /bin/bash because “SHELL=/bin/bash” is an entry in envp[].


if not found, it returns NULL

23
New cards

what does library fucntion setenv() do? what does it return?

it lets us create our own env var or modify an existing one. note: it does not actually change existing env vars, but only what we’re referencing in this program with envp[].


usage: setenv(“NAME”, “stored value”, overwrite-value);

where the overwrite-value is 0 if we don’t wanna overwrite, 1 if we wanna overwrite. NOTE: if overwrite is 0 and we try to modify an existing var, NOTHING happens (it’s not an error either).


it returns 0 for success and -1 for failure

24
New cards

what does library fucntion unsetenv() do? what does it return?

it removes an env var from our process envp[].

usage: unset(“NAME”)


it returns 0 for success and -1 for failure

25
New cards

what must we include in program to use strtok() ?

#include <string.h>

26
New cards

what does strtok() do, its arguments, and its return?

it splits a string into tokens.

usage: char *strtok(“string being split”, “delimiters”);


it returns tokens in order depending on how many times its called on that string (specifically, returns char pointer pointing to the beginning of the next token), or NULL if no more tokens exist

27
New cards

how does strtok() actually break down string into tokens?

it replaces all the specified delimiter(s) with \0 .

this means the actual string is updated with these null pointers, so BOTH the token returned from strtok() and the original string

28
New cards

how do we parse through tokens of strtok() and why?

on the first call, we do strtok(string, “delimiter”); but subsequently, we do:

strtok(NULL, “delimiter”); to make strtok start at the NEXT token instead of starting at the same spot in the string.


essentially, it uses two pointers. a saved internal pointer which always points to the beginning of the next token (right after \0 ) so you can use NULL to continue off, and a return pointer which returns the token just parsed.


caveat: saved internal pointer MAY point to a delimiter if there are consecutive delimiters

29
New cards

how are consecutive delimiters handled?

if there’s a token before the consecutive delmiiter, strtok() will deal with it normally but its saved internal pointer will point to a delimiter (the one after \0 from previous token).

THEN, using strtok() again replaces them all with \0 and skips over them to the start of the next token, meaning we do not ever return empty tokens from consecutive delimiters.

30
New cards

how are delimiters at the beginning and end of strings handled?

just like consecutive delimiters, they are ignored.

31
New cards

how is an infinite loop achieved (classic trap)?

char *token = strtok(str, delimiter);

while (token != NULL) {

	print(token); // pseudocode
	token = strtok(str, delimiter);

}

this is an infinite loop because we keep restarting the string and there is no saved internal pointer pointing to the next token. so we keep printing the first token over and over again cuz it hits that first delimiter.