Taking command line options in C -
i have hash table program , i'm trying implement command line option inputs. default action create hash table , read in text file, done after checking options. options alter properties of hash table before creation, e.g -f option specifies table size.
e.g ./program < words.txt -f 400
i'm handling them this:
int main(int argc, char*argv[]){ const char *optstring = "e:f:"; char option; int tablesize = 100; int unknown_words, i; char word[256]; htable h; default = 1; while((option = getopt(argc, argv, optstring)) != eof){ switch (option){ case 'e': default = 0; h = htable_new(tablesize); copy_in(h); unknown_words = find_words(h, optarg); printf("%d", unknown_words); break; case 'f': if(optarg && atoi(optarg)>0){ tablesize = atoi(optarg); } break; } } if(default==1){ h = htable_new(tablesize); copy_in(h); print_stats(h); } }
my issue want enter these flags/options in order. have option -e takes argument (the name of second text file). creates hash table , reads in first text file (like default action) searches hash table words in second file , prints unknown number of words. have option -f specifies use different table size default. if run below command expected behaviour.
./program < words.txt -f 350 -e other_words.txt
the -f option found first , tablesize variable changed default value given 350. -e option found , carried out using updated value.
however in different order same desired behaviour:
./program < words.txt -e other_words.txt -f 350
the -e option carried out on default table size , afterwards -f option found , tablesize changed , not used.
i've done below works seems inefficient. if -e option found, loop through remaining options , them first. means duplicate code each relevant option though , i'm curious how else handle this.
while((option = getopt(argc, argv, optstring)) != eof){ switch (option){ case 'e': default = 0; for(i=optind;i<argc;i++){ if(strcmp(argv[i],"-t") == 0){ if(argv[i+1] && atoi(argv[i+1])>0){ tablesize =atoi(argv[i+1]); } } } h = htable_new(tablesize); copy_in(h); unknown_words = find_words(h, optarg); printf("%d", unknown_words); break; case 'f': if(optarg && atoi(optarg)>0){ tablesize = atoi(optarg); } break; } }
the typical approach not actual work in option handlers; instead let each handler set variable keep track option specified (and argument was). after parse command line options, can process them in whatever order want. example, like:
const char* filename = null; int tablesize = 0; while ((option = getopt(argc, argv, optstring)) != eof) { switch (option) { case 'e': filename = optarg; break; case 'f': if (optarg && atoi(optarg) > 0) { tablesize = atoi(optarg); } break; } } if (filename != null) { default = 0; h = htable_new(tablesize); copy_in(h); unknown_words = find_words(h, filename); printf("%d", unknown_words); }
Comments
Post a Comment