14 * gcc prop_parse_du.c -o prop_parse_du -lprop -Wall -W -Wextra -ansi -pedantic
21 #include <prop/proplib.h>
23 #define INIT_ROOT_CAPACITY 100 /* root's dict initial capacity */
24 #define INIT_CHILD_CAPACITY 3 /* child's dict initial capacity */
30 prop_dictionary_t prd
= NULL
; /* root dictionary */
31 prop_dictionary_t pcd
= NULL
; /* child dictionary */
32 prop_string_t ps
= NULL
; /* path name */
33 prop_number_t pn
= NULL
; /* size in bytes */
38 char *tokens
[MAX_TOKENS
]; /* for du(1) output parse */
42 /* Initiate pipe stream to du(1) */
43 fp
= popen("du", "r");
47 /* Create root dictionary */
48 prd
= prop_dictionary_create_with_capacity(INIT_ROOT_CAPACITY
);
50 err(EXIT_FAILURE
, "prop_dictionary_create_with_capacity()");
52 /* Read from stream */
53 while (fgets(str
, MAX_STR
, fp
) != NULL
) {
54 /* Parse output of du(1) command */
56 p
= strtok_r(str
, "\t", &last
);
57 while (p
&& i
< MAX_TOKENS
- 1) {
59 p
= strtok_r(NULL
, "\t", &last
);
63 /* Trim '\n' from tokens[1] */
64 (tokens
[1])[strlen(tokens
[1]) - 1] = '\0';
66 /* Create child dictionary */
67 pcd
= prop_dictionary_create_with_capacity(INIT_CHILD_CAPACITY
);
69 err(EXIT_FAILURE
, "prop_dictionary_create_with_capacity()");
72 * tokens[0] holds the size in bytes
74 * We use a signed prop_number_t object, so that
75 * when externalized it will be represented as decimal
76 * (unsigned numbers are externalized in base-16).
78 * Note: atoi() does not detect errors, but we trust
79 * du(1) to provide us with valid input. Otherwise,
80 * we should use strtol(3) or sscanf(3).
82 pn
= prop_number_create_integer(atoi(tokens
[0]));
84 /* tokens[1] holds the path */
85 ps
= prop_string_create_cstring(tokens
[1]);
87 /* Add path to child dictionary */
88 if (prop_dictionary_set(pcd
, "path", ps
) == FALSE
)
89 err(EXIT_FAILURE
, "prop_dictionary_set()");
91 /* Add size to child dictionary */
92 if (prop_dictionary_set(pcd
, "size in bytes", pn
) == FALSE
)
93 err(EXIT_FAILURE
, "prop_dictionary_set()");
95 /* Add child dictionary to root dictionary */
96 if (prop_dictionary_set(prd
, tokens
[1], pcd
) == FALSE
)
97 err(EXIT_FAILURE
, "prop_dictionary_set()");
99 /* Release `pn' and `ps' */
100 prop_object_release(pn
);
101 prop_object_release(ps
);
103 /* Release child dictionary */
104 prop_object_release(pcd
);
107 /* Externalize root dictionary to file in XML representation */
108 if (prop_dictionary_externalize_to_file(prd
, "./data.xml") == FALSE
)
109 err(EXIT_FAILURE
, "prop_dictionary_externalize_to_file()");
111 /* Release root dictionary */
112 prop_object_release(prd
);
114 /* Close pipe stream */
115 if (pclose(fp
) == -1)
116 err(EXIT_FAILURE
, "pclose()");