Skip to content

Instantly share code, notes, and snippets.

@pbrisbin
Created December 21, 2010 15:55
Show Gist options
  • Select an option

  • Save pbrisbin/750100 to your computer and use it in GitHub Desktop.

Select an option

Save pbrisbin/750100 to your computer and use it in GitHub Desktop.
main.c
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>
/* email parsing from
* http://bytes.com/topic/c/answers/215251-regular-expressions-c
*/
void print_email(char str[])
{
char name[51];
char email[51];
int rc = sscanf(str, "%50[^<]<%50[^>]", name, email);
if (rc == 2)
{
printf("%s\t%s\n", email, name);
}
}
/* find the From: line in a file */
void find_from(char *fn)
{
FILE *file;
char line[1000];
bool found = false;
/* a hack for now */
int i = 1;
int limit = 100;
if (file = fopen(fn, "r"))
{
//while (!found && line != NULL) // no dice?
while (!found && i <= limit)
{
i++;
// todo: if it's never found, this never ends...
fgets(line, 1000, file);
if (strncmp("From: ", line, 6) == 0)
{
/* trim leading "From: " and trailing "\n" */
print_email(strndup(line + 6, strlen(line)-1));
found = true;
}
}
fclose(file);
}
else
{
printf("%s: failed to open file.\n", fn);
}
}
/* directory code from
* http://www.metalshell.com/source_code/116/Read_Directory.html
*/
int main(int argc, char *argv[])
{
DIR *dip;
struct dirent *dit;
char *fullpath;
char *filename;
if (argc < 2)
{
printf("usage: %s <directory>\n", argv[0]);
return 1;
}
if ((dip = opendir(argv[1])) == NULL)
{
perror("opendir");
return 1;
}
/* main loop */
while ((dit = readdir(dip)) != NULL)
{
fullpath = strdup(argv[1]);
filename = dit->d_name;
/* skip . and .. */
if (strcmp(filename, ".") != 0 && strcmp(filename, "..") != 0)
{
asprintf(&fullpath, "%s/%s", argv[1], filename);
find_from(fullpath);
free(fullpath);
}
}
if (closedir(dip) == -1)
{
perror("closedir");
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment