vmm: Moves gpci into guest_thread
[akaros.git] / user / parlib / opts.c
1 /* Copyright (c) 2016 Google Inc
2  * Barret Rhoden <brho@cs.berkeley.edu>
3  * See LICENSE for details.
4  *
5  * Various option parsing utility functions. */
6
7 #include <parlib/opts.h>
8 #include <stdio.h>
9 #include <errno.h>
10 #include <string.h>
11 #include <ctype.h>
12 #include <stdlib.h>
13
14 /* Parses an option file, calling parse() on individual lines.  We trim the
15  * lines of any leading or trailing spaces first, and ignore anything after #.
16  */
17 int parse_opts_file(char *opts_file, void (*parse)(char *))
18 {
19         char *line = NULL;
20         size_t len = 0;
21         ssize_t read;
22         FILE *fp;
23         char *_line;
24
25         if (!opts_file)
26                 return 0;
27         fp = fopen(opts_file, "r");
28         if (!fp)
29                 return -1;
30         while ((read = getline(&line, &len, fp)) != -1) {
31                 _line = line;
32                 /* Drop comments */
33                 for (int i = 0; i < read; i++) {
34                         if (_line[i] == '#') {
35                                 _line[i] = 0;
36                                 read = i;
37                                 break;
38                         }
39                 }
40                 if (!read)
41                         continue;
42                 /* Drop trailing spaces */
43                 for (int i = read - 1; i >= 0; i--) {
44                         if (isspace(_line[i]))
45                                 _line[i] = 0;
46                         else
47                                 break;
48                 }
49                 while (isspace(_line[read - 1])) {
50                         _line[read - 1] = 0;
51                         read--;
52                         if (!read)
53                                 continue;
54                 }
55                 /* Drop leading spaces */
56                 while (isspace(_line[0]))
57                         _line++;
58                 parse(_line);
59         }
60         free(line);
61         fclose(fp);
62         return 0;
63 }