# The following program shows how to use SRgetopt to process # a command that takes the options 'a', 'b', 'f', and 'w' where # 'f' is followed by a file name and 'w' is followed by an integer. # Any other option causes getopt to print an error message and # return a '?', and the program terminates with a stop. # (Based on the example contained in SRgetopt.sr distributed with SR.) resource test_getopt() import SRgetopt var ch: char # process options in command line arguments var aflg : int := 0 # set var bflg : bool := false # option var filename: string[optMAXLEN] := "out" # default var width : int := 80 # values do (ch := getopt("abf:w:")) != optEOF -> if ch = 'a' -> aflg++ [] ch = 'b' -> bflg := true [] ch = 'f' -> filename := optarg [] ch = 'w' -> width := int(optarg) [] else -> stop(1) # catch undefined options here, fi # getopt returns '?' od write("-a", aflg) write("-b", bflg) write("-f", filename) write("-w", width) # process non-option command line arguments fa k := optind to numargs() -> # getopt sets optind var carg: string[40] getarg(k, carg) write("normal argument", k, "is", carg) af end test_getopt /* ............... Example compile and run(s) % sr -o test_getopt test_getopt.sr % ./test_getopt -a 0 -b false -f out -w 80 % ./test_getopt a1 a2 a3 -a 0 -b false -f out -w 80 normal argument 1 is a1 normal argument 2 is a2 normal argument 3 is a3 % ./test_getopt -a -b -f abc -w123 a1 a2 a3 -a 1 -b true -f abc -w 123 normal argument 6 is a1 normal argument 7 is a2 normal argument 8 is a3 % ./test_getopt -x a1 a2 a3 ./test_getopt: illegal option -- x % ./test_getopt -a -fabc -x -w 123 -fdef a1 a2 a3 ./test_getopt: illegal option -- x % ./test_getopt -a -fabc -a -w 123 -f def a1 a2 a3 -a 2 -b false -f def -w 123 normal argument 8 is a1 normal argument 9 is a2 normal argument 10 is a3 % ./test_getopt -a -f -w123 -a a1 a2 a3 -a 2 -b false -f -w123 -w 80 normal argument 5 is a1 normal argument 6 is a2 normal argument 7 is a3 % ./test_getopt -a -f -w 123 -a a1 a2 a3 -a 1 -b false -f -w -w 80 normal argument 4 is 123 normal argument 5 is -a normal argument 6 is a1 normal argument 7 is a2 normal argument 8 is a3 % ./test_getopt -b -w123 -f a1 a2 a3 -a 0 -b true -f a1 -w 123 normal argument 5 is a2 normal argument 6 is a3 % ./test_getopt -a -f ./test_getopt: option requires an argument -- f % ./test_getopt -a -ab -a -b a1 a2 a3 -a 3 -b true -f out -w 80 normal argument 5 is a1 normal argument 6 is a2 normal argument 7 is a3 % ./test_getopt -a -w abc -f 123 a1 a2 a3 RTS abort: file test_getopt.sr, line 20: illegal conversion: int("abc") % ./test_getopt -a 123 -f abc a1 a2 a3 -a 1 -b false -f out -w 80 normal argument 2 is 123 normal argument 3 is -f normal argument 4 is abc normal argument 5 is a1 normal argument 6 is a2 normal argument 7 is a3 % ./test_getopt -a123 -f def a1 a2 a3 ./test_getopt: illegal option -- 1 % ./test_getopt -a -babc -f def -w 123 a1 a2 a3 ./test_getopt: illegal option -- c */