UTF-16 reading and writing with C

It seems almost no one does this kind of stuff with C, it was very hard to find material for this on the net. So I thought of posting it so that everyone can benefit. The code is for an XML/HTML tag stripper, which strips all tags. Make sure you keep the error checker intact, it spits out some uncommon errors that at first glance you won’t know what it’s talking about.

A major plus point in using “ccs=UTF16[BE|LE]” is that it handles endianness and BOM automatically. But you have to know what you are dealing with, I *think* “ccs=UTF16” has Native Endianness, which means LE for majority of PCs that are in use the files I got to strip were BE and LE mixed so I had to check BOM manually; 0xFF 0xFE is Little Endian.

Note: This code was only tested on Linux, it should work without any changes on any POSIX system. Windows is a different story as always it may need some changes in “ccs=…” part I saw in some material UTF-16BE/UTF-16LE has been used, but it didn’t work on Linux that way if this code doesn’t work on Windows you might have to change to that.

#include <stdio.h>
#include <wchar.h>
#include <errno.h>
#include <string.h>

int main(int argc, char *argv[])
	int i;
	for (i=1;i<argc;i++){
		FILE *o=fopen(argv[i],"r");
		FILE *f;
		if (fgetc(o)!=0xFF){
		} else {

		char new[32];
		FILE *g=fopen(new,"w,ccs=UTF16LE");

		int write=1;
		wint_t c=fgetwc(f);
		while (c!=WEOF) {
			if (c==L'<')

			if (write){
			if (c==L'>')



	return 0;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s