fopen for everything - is this possible?

Viewed 5498

I used to programing windows, but I want to try my hand on making a cross-platform application. And I have some questions, if you don't mind:

Question 1

Is there some way to open UNICODE\ASCII file and automatically detect it's encoding using bare ANSI C. MSDN says that fopen() can switch between various UNICODE formats (utf-8, utf-16, UNICODE BI\LI) if I will use "ccs=UNICODE" flag. It has been found experimentally that switching from UNICODE to ASCII is not happening, but trying to solve this problem, I discovered that text Unicode files has some prefixes like 0xFFFE, 0xFEFF, or 0xFEBB.

FILE *file;
{
 __int16 isUni;
 file = _tfopen(filename, _T("rb"));
 fread(&(isUni),1,2,file);
 fclose(file);
 if( isUni == (__int16)0xFFFE || isUni == (__int16)0xFEFF || isUni == (__int16)0xFEBB)
  file = _tfopen(filename, _T("r,ccs=UNICODE"));
 else
  file = _tfopen(filename, _T("r"));         
}

So, can I make something like this cross-platform and not so ugly?

Question 2

I can do something like this in windows, but will it work in Linux?

file = fopen(filename, "r");
fwscanf(file,"%lf",buffer);

If not, then is there some sort of ANSI C function to convert ASCII strings to Unicode? I want to work with Unicode strings in my program .

Question 3

Besides, I need to output Unicode strings into console. There is setlocale(*) in windows, but what should I do in Linux? It seems that console is already Unicode there.

Question 4

Generally speaking, I want to work with Unicode in my program, but I faced some strange problems:

f = fopen("inc.txt","rt");
fwprintf(f,L"Текст");            // converted successfully
fclose(f);
f = fopen("inc_u8.txt","rt, ccs = UNICODE");
fprintf(f,"text");               // failed to convert
fclose(f);

P.S. Is there some good book about cross-platform programming, something with comparison of windows and linux programs code? And some book about ways of using Unicode, practical methods, that is. I don't want to immerse in plain UNICODE BI\LI history, I am interested in specific C/C++ libraries.

2 Answers
Related