Skip to content

Instantly share code, notes, and snippets.

@Leandros
Created May 19, 2017 08:15
Show Gist options
  • Save Leandros/d7006718050a3ade582ad9c1fa315ff9 to your computer and use it in GitHub Desktop.
Save Leandros/d7006718050a3ade582ad9c1fa315ff9 to your computer and use it in GitHub Desktop.
remove bom. usage: gcc -o nobom nobom.c && ./nobom path/to/file
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
static char bom[3] = { 0xEF, 0xBB, 0xBF };
#define error(msg) error__(msg, __LINE__)
static int
error__(char const *msg, int line)
{
fprintf(stderr, "Error: %s (at line %d)\n", msg, line);
return 1;
}
int
main(int argc, char *argv[])
{
FILE *f;
size_t r, n;
long size;
char *new;
char buf[8192];
char path[255];
if (argc != 2)
return error("missing arguments");
if ((f = fopen(argv[1], "rb")) == NULL)
return error("fopen()");
if ((r = fread(buf, 1, 3, f)) != 3)
return error("fread()");
if (memcmp(buf, bom, 3) != 0)
return 0;
if (fseek(f, 0, SEEK_END))
return error("fseek()");
if ((size = ftell(f)) == -1)
return error("ftell()");
if (fseek(f, 3, SEEK_SET))
return error("fseek()");
size -= 3;
if ((new = malloc(size + 1)) == NULL)
return error("malloc()");
n = 0;
while ((r = fread(buf, 1, 8192, f)) > 0)
memcpy(new + n, buf, r), n += r;
if (fclose(f))
return error("fclose()");
if ((f = fopen(argv[1], "w")) == NULL)
return error("fopen()");
if (fwrite(new, 1, size, f) != size)
return error("fwrite()");
if (fclose(f))
return error("fclose()");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment