This source file includes following definitions.
- argv_iter_init_argv
- argv_iter_init_stream
- argv_iter
- argv_iter_n_args
- argv_iter_free
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #include <config.h>
20 #include "argv-iter.h"
21
22 #include <stdlib.h>
23 #include <string.h>
24
25 struct argv_iterator
26 {
27
28
29 FILE *fp;
30 size_t item_idx;
31 char *tok;
32 size_t buf_len;
33
34
35 char **arg_list;
36 char **p;
37 };
38
39 struct argv_iterator *
40 argv_iter_init_argv (char **argv)
41 {
42 struct argv_iterator *ai = malloc (sizeof *ai);
43 if (!ai)
44 return NULL;
45 ai->fp = NULL;
46 ai->arg_list = argv;
47 ai->p = argv;
48 return ai;
49 }
50
51
52
53 struct argv_iterator *
54 argv_iter_init_stream (FILE *fp)
55 {
56 struct argv_iterator *ai = malloc (sizeof *ai);
57 if (!ai)
58 return NULL;
59 ai->fp = fp;
60 ai->tok = NULL;
61 ai->buf_len = 0;
62
63 ai->item_idx = 0;
64 ai->arg_list = NULL;
65 return ai;
66 }
67
68 char *
69 argv_iter (struct argv_iterator *ai, enum argv_iter_err *err)
70 {
71 if (ai->fp)
72 {
73 ssize_t len = getdelim (&ai->tok, &ai->buf_len, '\0', ai->fp);
74 if (len < 0)
75 {
76 *err = feof (ai->fp) ? AI_ERR_EOF : AI_ERR_READ;
77 return NULL;
78 }
79
80 *err = AI_ERR_OK;
81 ai->item_idx++;
82 return ai->tok;
83 }
84 else
85 {
86 if (*(ai->p) == NULL)
87 {
88 *err = AI_ERR_EOF;
89 return NULL;
90 }
91 else
92 {
93 *err = AI_ERR_OK;
94 return *(ai->p++);
95 }
96 }
97 }
98
99 size_t
100 argv_iter_n_args (struct argv_iterator const *ai)
101 {
102 return ai->fp ? ai->item_idx : ai->p - ai->arg_list;
103 }
104
105 void
106 argv_iter_free (struct argv_iterator *ai)
107 {
108 if (ai->fp)
109 free (ai->tok);
110 free (ai);
111 }