Add comments regarding use of atoi()
[eleutheria.git] / proplib / prop_du.c
blob8b7484a0fe9b0cde1b0e7a4121eb83cd95dadd1f
1 #include <err.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/wait.h> /* for waitpid() macros */
6 #include <prop/proplib.h>
8 #define INIT_CAPACITY 100
9 #define MAX_STR 100
10 #define MAX_TOKENS 3
12 int main(void)
14 char str[MAX_STR];
15 char *tokens[MAX_TOKENS]; /* for ``du'' output parse */
16 char *last, *p;
17 int i, ret;
18 FILE *fp;
19 prop_dictionary_t pd;
20 prop_number_t pn;
22 /* Initiate pipe stream to ``du'' */
23 fp = popen("du", "r");
24 if (fp == NULL) {
25 perror("popen()");
26 exit(EXIT_FAILURE);
29 /* Create dictionary */
30 pd = prop_dictionary_create_with_capacity(INIT_CAPACITY);
31 if (pd == NULL) {
32 pclose(fp);
33 errx(EXIT_FAILURE, "prop_dictionary_create_with_capacity()");
36 /* Read from stream */
37 while (fgets(str, MAX_STR, fp) != NULL) {
38 /* Parse output of ``du'' command */
39 i = 0;
40 p = strtok_r(str, "\t", &last);
41 while (p && i < MAX_TOKENS - 1) {
42 tokens[i++] = p;
43 p = strtok_r(NULL, "\t", &last);
45 tokens[i] = NULL;
47 /* Trim '\n' from tokens[1] */
48 (tokens[1])[strlen(tokens[1]) - 1] = '\0';
51 * We use a signed prop_number_t object, so that
52 * when externalized it will be represented as decimal
53 * (unsigned numbers are externalized in base-16).
55 * Note: atoi() does not detect errors, but we trust
56 * ``du'' to provide us with valid input. Otherwise,
57 * we should use strtol(3) or sscanf(3).
59 pn = prop_number_create_integer(atoi(tokens[0]));
61 /* Add a <path, size> pair in our dictionary */
62 if (prop_dictionary_set(pd, tokens[1], pn) == FALSE) {
63 prop_object_release(pn);
64 prop_object_release(pd);
65 errx(EXIT_FAILURE, "prop_dictionary_set()");
68 /* Release prop_number_t object */
69 prop_object_release(pn);
72 /* Externalize dictionary to file in XML representation */
73 if (prop_dictionary_externalize_to_file(pd, "./data.xml") == FALSE) {
74 prop_object_release(pd);
75 errx(EXIT_FAILURE, "prop_dictionary_externalize_to_file()");
78 /* Release dictionary */
79 prop_object_release(pd);
81 /* Close pipe stream */
82 ret = pclose(fp);
83 if (ret == -1) {
84 perror("pclose()");
85 exit(EXIT_FAILURE);
88 return EXIT_SUCCESS;