summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 56d8523185cb95ef98d70423eded2cf789632e62 (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
#include <unistd.h>
#include <stdio.h>
#include <iconv.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>


int main(int argc, char **argv)
{
	int opt = -1;
	char ifile[256], ofile[256], fcharset[32], tcharset[32];
	ifile[0] = 0;
	ofile[0] = 0;
	fcharset[0] = 0;
	tcharset[0] = 0;
	while((opt = getopt(argc, argv, "i:o:f:t:")) != -1)
	{
		switch(opt)
		{
			case 'i':
			strcpy(ifile, optarg);
			break;
			case 'o':
			strcpy(ofile, optarg);
			break;
			case 'f':
			strcpy(fcharset, optarg);
			break;
			case 't':
			strcpy(tcharset, optarg);
			break;
			default:
			printf("usage: %s -ioft\n\t-i input file\n\t-o output file\n\t-f from charset\n\t-t to charset\n", argv[0]);
		}
	}
	iconv_t id = iconv_open(tcharset, fcharset);
	if((long)id == -1)
	{
		printf("failed to create iconv descriptor with error: %s\n", strerror(errno));
		return 1;
	}
	FILE *in = fopen(ifile, "r");
	if(!in)
	{
		printf("failed to open input file with error: %s\n", strerror(errno));
		return 1;
	}
	FILE *out = fopen(ofile, "w");
	if(!out)
	{
		printf("failed to open input file with error: %s\n", strerror(errno));
		return 1;
	}
	while(!feof(in))
	{
		char *buf = (char*)malloc(4096), *outbuf = (char*)malloc(4096), *op, *ip;
		op = outbuf;
		ip = buf;
		if(!fgets(buf, 4096, in))
			break;
		size_t len = strlen(buf), outlen = 4096;
		int enc_len = iconv(id, &ip, &len, &op, &outlen);
		if(enc_len == -1)
		{
			printf("failed to convert buffer with error: %s\n", strerror(errno));
			return 1;
		}
		enc_len = 4096 - outlen;
		if((int)fwrite(outbuf, 1, enc_len, out) != enc_len)
		{
			printf("failed to write data to file with error: %s\n", strerror(errno));
			return 1;
		}
		free(buf);
		free(outbuf);
	}
	return 0;
}