/* $Id: split_std_mailbox.cc 2842 2007-12-02 02:37:59Z flaterco $ */ // g++ -Wall -Wextra -pedantic -O2 -s -o split_std_mailbox split_std_mailbox.cc -ldstr #include #include #include #include #include #include #include FILE *newmsg (char *dest_dir) { static const unsigned bufsize = 1000; static unsigned long serialnum = 0; size_t l; char msgfilename[bufsize]; FILE *fp; struct stat stat_struct; l = strlen(dest_dir); assert (l > 0); assert (l + 80 < bufsize); strcpy (msgfilename, dest_dir); if (msgfilename[l-1] != '/') msgfilename[l++] = '/'; do sprintf (msgfilename+l, "msg%lu", serialnum++); while (stat (msgfilename, &stat_struct) == 0); if (!(fp = fopen (msgfilename, "w"))) { perror (msgfilename); fprintf (stderr, "Aborting run\n"); exit (-1); } return fp; } int main (int argc, char **argv) { FILE *mbox, *msg=NULL; Dstr inbuf; bool prevLineBlank (true); if (argc != 3) { fprintf (stderr, "Usage: split_std_mailbox mailbox-filename destination-directory\n"); exit (-1); } if (!(mbox = fopen (argv[1], "r"))) { perror (argv[1]); exit (-1); } while (!inbuf.getline(mbox).isNull()) { // Had trouble with unquoted Froms in messages. The address // condition would be too restrictive on systems where local mail // gets use. if (prevLineBlank && (inbuf.strchr('@') != -1 || inbuf.strstr("MAILER-DAEMON") != -1 || !(strncmp (inbuf.aschar(), "From <>", 7))) && !(strncmp (inbuf.aschar(), "From ", 5))) { if (msg) fclose (msg); msg = newmsg (argv[2]); } fprintf (msg, "%s\n", inbuf.aschar()); prevLineBlank = (inbuf.length() == 0); } fclose (mbox); if (msg) fclose (msg); return 0; }