3 * gcc prop_du.c -o prop_du -lprop -Wall -W -Wextra -ansi -pedantic
10 #include <prop/proplib.h>
12 #define INIT_CAPACITY 100
19 char *tokens
[MAX_TOKENS
]; /* for du(1) output parse */
23 prop_dictionary_t prd
; /* root dictionary */
24 prop_dictionary_t pcd
; /* child dictionary */
28 /* Initiate pipe stream to du(1) */
29 fp
= popen("du", "r");
35 /* Create root dictionary */
36 prd
= prop_dictionary_create_with_capacity(INIT_CAPACITY
);
39 err(EXIT_FAILURE
, "prop_dictionary_create_with_capacity()");
42 /* Read from stream */
43 while (fgets(str
, MAX_STR
, fp
) != NULL
) {
44 /* Parse output of du(1) command */
46 p
= strtok_r(str
, "\t", &last
);
47 while (p
&& i
< MAX_TOKENS
- 1) {
49 p
= strtok_r(NULL
, "\t", &last
);
53 /* Trim '\n' from tokens[1] */
54 (tokens
[1])[strlen(tokens
[1]) - 1] = '\0';
56 /* Create child dictionary */
57 pcd
= prop_dictionary_create_with_capacity(INIT_CAPACITY
);
59 prop_object_release(prd
);
60 err(EXIT_FAILURE
, "prop_dictionary_create_with_capacity()");
63 /* tokens[1] holds the path */
64 ps
= prop_string_create_cstring(tokens
[1]);
67 * tokens[0] holds the size in bytes
69 * We use a signed prop_number_t object, so that
70 * when externalized it will be represented as decimal
71 * (unsigned numbers are externalized in base-16).
73 * Note: atoi() does not detect errors, but we trust
74 * du(1) to provide us with valid input. Otherwise,
75 * we should use strtol(3) or sscanf(3).
77 pn
= prop_number_create_integer(atoi(tokens
[0]));
79 /* Add path to child dictionary */
80 if (prop_dictionary_set(pcd
, "path", ps
) == FALSE
) {
81 prop_object_release(pn
);
82 prop_object_release(ps
);
83 prop_object_release(pcd
);
84 prop_object_release(prd
);
87 /* Add size to child dictionary */
88 if (prop_dictionary_set(pcd
, "size in bytes", pn
) == FALSE
) {
89 prop_object_release(pn
);
90 prop_object_release(pcd
);
91 prop_object_release(prd
);
92 err(EXIT_FAILURE
, "prop_dictionary_set()");
95 /* Release prop_number_t object */
96 prop_object_release(pn
);
97 prop_object_release(ps
);
99 /* Add child dictionary to root dictionary */
100 prop_dictionary_set(prd
, tokens
[1], pcd
);
102 /* Release child dictionary */
103 prop_object_release(pcd
);
106 /* Externalize dictionary to file in XML representation */
107 if (prop_dictionary_externalize_to_file(prd
, "./data.xml") == FALSE
) {
108 prop_object_release(prd
);
109 err(EXIT_FAILURE
, "prop_dictionary_externalize_to_file()");
112 /* Release root dictionary */
113 prop_object_release(prd
);
115 /* Close pipe stream */
116 if (pclose(fp
) == -1)
117 err(EXIT_FAILURE
, "pclose()");