messages.c
2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "config.h"
#include <mailutils/mailutils.h>
#include <stdio.h>
#include <argp.h>
static int messages_count (char *);
const char *argp_program_version = "messages (" PACKAGE ") " VERSION;
const char *argp_program_bug_address = "<bug-mailutils@gnu.org>";
static char doc[] = "GNU messages -- count the number of messages in a mailbox";
static char args_doc[] = "[mailbox...]";
static struct argp_option options[] = {
{"quiet", 'q', 0, 0, "Only display number of messages"},
{"silent", 's', 0, 0, "Same as -q"},
{ 0 }
};
struct arguments
{
int argc;
char **argv;
};
/* are we loud or quiet? */
static int silent = 0;
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
struct arguments *args = state->input;
switch (key)
{
case 'q':
case 's':
silent = 1;
break;
case ARGP_KEY_ARG:
args->argv = realloc (args->argv,
sizeof (char *) * (state->arg_num + 2));
args->argv[state->arg_num] = arg;
args->argv[state->arg_num + 1] = NULL;
args->argc++;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc };
int
main (int argc, char **argv)
{
int i = 1;
list_t bookie;
int err = 0;
struct arguments args = {0, NULL};
argp_parse (&argp, argc, argv, 0, 0, &args);
registrar_get_list (&bookie);
list_append (bookie, path_record);
if (args.argc < 1 && messages_count (getenv("MAIL")) < 0)
err = 1;
else if (args.argc >= 1)
{
for (i=0; i < args.argc; i++)
if (messages_count (args.argv[i]) < 0)
err = 1;
}
return err;
}
static int
messages_count (char *box)
{
mailbox_t mbox;
int count;
if (mailbox_create_default (&mbox, box) != 0)
{
fprintf (stderr, "Couldn't create mailbox %s.\n", box);
return -1;
}
if (mailbox_open (mbox, MU_STREAM_READ) != 0)
{
fprintf (stderr, "Couldn't open mailbox %s.\n", box);
return -1;
}
if (mailbox_messages_count (mbox, &count) != 0)
{
fprintf (stderr, "Couldn't count messages in %s.\n", box);
return -1;
}
if (silent)
printf ("%d\n", count);
else
printf ("Number of messages in %s: %d\n", box, count);
if (mailbox_close (mbox) != 0)
{
fprintf (stderr, "Couldn't close %s.\n", box);
return -1;
}
mailbox_destroy (&mbox);
return count;
}