summaryrefslogtreecommitdiff
path: root/insertbom.c
blob: 7d45faeb0ad934d81ded805d12fcbee38ff985ca (plain)
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
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/stat.h>

static off_t Size(const char *name)
{
    struct stat st = {0};

    stat(name, &st);

    return st.st_size;
}

static void Handle(const char *name)
{
    FILE *fp = NULL;
    off_t len = Size(name);
    unsigned char *buff = NULL;
    int write = 0;

    if (len < 3)
    {
    	printf("%s: too short\n", name);
	return;
    }

    buff = malloc(len + 2);
    fp = fopen(name, "rb");
    fread(buff, 1, len, fp);
    fclose(fp);

    if ((buff[0] == 0xffu && buff[1] == 0xfeu) ||
    	(buff[0] == 0xfeu && buff[1] == 0xffu))
    {
    	printf("%s: already has BOM\n", name);
	free(buff);
	return;
    }

    if (buff[0] == 0 && isprint(buff[1]))
    {
    	printf("%s: Guessing BE UTF-16\n", name);
	write = 1;
	memmove(buff + 2, buff, len);
	buff[0] = 0xfe;
	buff[1] = 0xff;
    }
    else if (buff[1] == 0 && isprint(buff[0]))
    {
    	printf("%s: Guessing LE UTF-16\n", name);
	write = 1;
	memmove(buff + 2, buff, len);
	buff[0] = 0xff;
	buff[1] = 0xfe;
    }
    else
    {
    	printf("%s: Leaving alone\n", name);
    }

    if (write)
    {
    	fp = fopen(name, "wb");
	fwrite(buff, 1, len + 2, fp);
	fclose(fp);
    }

    free(buff);
}

int main(int argc, char *argv[])
{
    int f;

    for(f = 1; f < argc; f++)
    {
    	Handle(argv[f]);
    }
}