Skip to content

Instantly share code, notes, and snippets.

@sheeit
Last active July 6, 2018 14:22
Show Gist options
  • Save sheeit/dcaae4d753ff5dec02ce17ff818a4e2e to your computer and use it in GitHub Desktop.
Save sheeit/dcaae4d753ff5dec02ce17ff818a4e2e to your computer and use it in GitHub Desktop.
Behead: remove email headers, and print the body to stdout.
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void behead(FILE *f);
void *end_of_line(char *line, size_t size, FILE *f);
void append(char *tmp, size_t size, const char *line, size_t len);
int main(int argc, char *argv[])
{
FILE *f = stdin;
bool f_is_stdin = true;
if (argc > 1) {
f = fopen(argv[1], "rb");
f_is_stdin = false;
}
if (!f) {
perror(argv[1]);
exit(EXIT_FAILURE);
}
behead(f);
if (!f_is_stdin) {
fclose(f);
}
exit(EXIT_SUCCESS);
}
void append(char *tmp, size_t size, const char *line, size_t len)
{
size_t i, j;
--size;
for (i = len; i < size; ++i) {
tmp[i - len] = tmp[i];
}
for (i = size - len, j = 0; i < size && j <= len; ++i, ++j) {
tmp[i] = line[j];
}
return;
}
void *end_of_line(char *line, size_t size, FILE *f)
{
char *tmp = malloc(size);
void *r;
size_t len;
if (!tmp)
return NULL;
r = (void *) fgets(line, size, f);
if (line[0] == '\n' || !r)
goto exit;
len = strlen(line);
while (len == 0 || line[len - 1] != '\n') {
strncpy(tmp, line, size);
if ((r = (void *) fgets(line, size, f)) == NULL)
goto exit;
len = strlen(line);
append(tmp, size, line, len);
}
strncpy(line, tmp, size);
exit:
if (tmp)
free(tmp);
return r;
}
void behead(FILE *f)
{
char line[16];
size_t chars_read;
while (end_of_line(line, sizeof(line), f) != NULL)
if (line[0] == '\n' && line[1] == '\0')
break;
while ((chars_read = fread(line, 1, sizeof(line), f)) > 0u) {
size_t written = fwrite(line, 1, chars_read, stdout);
if (written != chars_read)
perror("written != read");
}
}
@sheeit
Copy link
Author

sheeit commented Feb 14, 2018

Doesn't work with files with CRLF line endings for some reason.

Fixed. Oddly, I fixed this issue by not worrying about it, and ignoring it altogether.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment