打开任何文件 - 这是可能的吗?

24
我曾经编写Windows程序,但现在想尝试制作跨平台应用程序。如果您不介意,我有一些问题: 问题1 是否有一种方法可以使用裸的ANSI C打开UNICODE\ASCII文件并自动检测其编码? MSDN表示,如果使用“ccs = UNICODE”标志,则fopen()可以在各种UNICODE格式(utf-8,utf-16,UNICODE BI \ LI)之间切换。实验发现从UNICODE转换为ASCII不会发生,但是尝试解决此问题时,我发现文本Unicode文件具有0xFFFE、0xFEFF或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"));         
}

那么,我能否制作类似于此的跨平台且不那么丑陋的内容?

问题2

我可以在Windows上做这样的事情,但在Linux上行得通吗?

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

如果没有,那么是否有一种ANSI C函数可以将ASCII字符串转换为Unicode?我想在我的程序中使用Unicode字符串。
问题3:此外,我需要将Unicode字符串输出到控制台。在Windows中有setlocale(*),但在Linux中应该怎么做呢?似乎控制台已经是Unicode了。
问题4:总的来说,我想在我的程序中使用Unicode,但是我遇到了一些奇怪的问题:
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);

附言:有没有一些关于跨平台编程的好书,比如比较Windows和Linux程序代码的书?还有一些关于使用Unicode的方法的书,实用方法,我不想深入研究纯粹的UNICODE BI\LI历史,我对特定的C/C++库很感兴趣。


3
我认为将ccs=任何东西不是标准的写法,因此它不具备可移植性。 - ShinTakezou
ANSI C不支持UNICODE,它支持wchar_t,但是wchar_t并不是UNICODE,因此->无法实现。 - user411313
2
以FE和FF字节开头的文件可能是大端UTF-16编码。如果以FF,FE开头,则可能是小端UTF-16编码。这两个字节是一个16位BOM(字节顺序标记),用于区分大端和小端(实际上它们是编码为“零宽度不间断空格”的字符)。一些UTF-8文件也以编码的BOM开头(将是3个字节),但大多数不会。在没有BOM或一些超过127的字节的情况下,ASCII文件和等效的UTF-8文件之间实际上没有任何区别。 - Keith Thompson
2
Unicode目前还不是C标准的一部分。它可能会在C1X中被添加,但我们还要观察。在那之前,请查看libicu - maep
谢谢您的建议,但对于小项目来说,ICU是否太重了?我的意思是它真的那么常规吗? - Anonymous
显示剩余3条评论
2个回答

2

问题1:

如果你的文件有字节顺序标记,你可以检测到它,这是你发现的字节序列。在谷歌和stackoverflow上搜索就可以找到相关信息。至于“不那么丑陋”的方案:你可以重构/美化你的代码,例如编写一个用于确定BOM的函数,并在开头执行,然后根据需要调用fopen或_tfopen。然后你还可以再次重构,编写自己的fopen函数。但它仍然会很丑陋。

问题2:

是的,但是Linux上的unicode函数名称与Windows上的不一定相同。使用定义。也许编写自己的TCHAR.H。

问题3:

#include <locale.h>
setlocale(LC_ALL, "en.UTF-8")

man 3 setlocale

第四个问题:
只需使用fwprintf。
另一个不是标准。

您可以使用wxWidgets工具包。
它使用unicode,并且使用在Windows和Linux和Unix和Mac上实现相同事物的类。

对于您来说更好的问题是如何将ASCII转换为Unicode,反之亦然。 操作如下:

std::string Unicode2ASCII( std::wstring wstrStringToConvert )
{
    size_t sze_StringLength = wstrStringToConvert.length()  ;

    if(0 == sze_StringLength)
        return "" ;

    char* chrarry_Buffer = new char[ sze_StringLength + 1 ] ;
    wcstombs( chrarry_Buffer, wstrStringToConvert.c_str(), sze_StringLength ) ; // Unicode2ASCII, const wchar_t* C-String 2 mulibyte C-String
    chrarry_Buffer[sze_StringLength] = '\0'     ;
    std::string strASCIIstring = chrarry_Buffer ;
    delete chrarry_Buffer ;

    return strASCIIstring ;
}


std::wstring ASCII2Unicode( std::string strStringToConvert )
{
    size_t sze_StringLength = strStringToConvert.length() ;

    if(0 == sze_StringLength)
        return L"" ;

    wchar_t* wchrarry_Buffer = new wchar_t[ sze_StringLength + 1 ] ;
    mbstowcs( wchrarry_Buffer, strStringToConvert.c_str(), sze_StringLength ) ; // Unicode2ASCII, const. mulibyte C-String 2 wchar_t* C-String
    wchrarry_Buffer[sze_StringLength] = L'\0'    ;
    std::wstring wstrUnicodeString = wchrarry_Buffer ;
    delete wchrarry_Buffer   ;

    return wstrUnicodeString ;
}

编辑: 以下是关于Linux(wchar.h)上可用的Unicode函数的一些见解:

__BEGIN_NAMESPACE_STD
/* Copy SRC to DEST.  */
extern wchar_t *wcscpy (wchar_t *__restrict __dest,
            __const wchar_t *__restrict __src) __THROW;
/* Copy no more than N wide-characters of SRC to DEST.  */
extern wchar_t *wcsncpy (wchar_t *__restrict __dest,
             __const wchar_t *__restrict __src, size_t __n)
     __THROW;

/* Append SRC onto DEST.  */
extern wchar_t *wcscat (wchar_t *__restrict __dest,
            __const wchar_t *__restrict __src) __THROW;
/* Append no more than N wide-characters of SRC onto DEST.  */
extern wchar_t *wcsncat (wchar_t *__restrict __dest,
             __const wchar_t *__restrict __src, size_t __n)
     __THROW;

/* Compare S1 and S2.  */
extern int wcscmp (__const wchar_t *__s1, __const wchar_t *__s2)
     __THROW __attribute_pure__;
/* Compare N wide-characters of S1 and S2.  */
extern int wcsncmp (__const wchar_t *__s1, __const wchar_t *__s2, size_t __n)
     __THROW __attribute_pure__;
__END_NAMESPACE_STD

#ifdef __USE_XOPEN2K8
/* Compare S1 and S2, ignoring case.  */
extern int wcscasecmp (__const wchar_t *__s1, __const wchar_t *__s2) __THROW;

/* Compare no more than N chars of S1 and S2, ignoring case.  */
extern int wcsncasecmp (__const wchar_t *__s1, __const wchar_t *__s2,
            size_t __n) __THROW;

/* Similar to the two functions above but take the information from
   the provided locale and not the global locale.  */
# include <xlocale.h>

extern int wcscasecmp_l (__const wchar_t *__s1, __const wchar_t *__s2,
             __locale_t __loc) __THROW;

extern int wcsncasecmp_l (__const wchar_t *__s1, __const wchar_t *__s2,
              size_t __n, __locale_t __loc) __THROW;
#endif


/* Special versions of the functions above which take the locale to
   use as an additional parameter.  */
extern long int wcstol_l (__const wchar_t *__restrict __nptr,
              wchar_t **__restrict __endptr, int __base,
              __locale_t __loc) __THROW;

extern unsigned long int wcstoul_l (__const wchar_t *__restrict __nptr,
                    wchar_t **__restrict __endptr,
                    int __base, __locale_t __loc) __THROW;

__extension__
extern long long int wcstoll_l (__const wchar_t *__restrict __nptr,
                wchar_t **__restrict __endptr,
                int __base, __locale_t __loc) __THROW;

__extension__
extern unsigned long long int wcstoull_l (__const wchar_t *__restrict __nptr,
                      wchar_t **__restrict __endptr,
                      int __base, __locale_t __loc)
     __THROW;

extern double wcstod_l (__const wchar_t *__restrict __nptr,
            wchar_t **__restrict __endptr, __locale_t __loc)
     __THROW;

extern float wcstof_l (__const wchar_t *__restrict __nptr,
               wchar_t **__restrict __endptr, __locale_t __loc)
     __THROW;

extern long double wcstold_l (__const wchar_t *__restrict __nptr,
                  wchar_t **__restrict __endptr,
                  __locale_t __loc) __THROW;


/* Copy SRC to DEST, returning the address of the terminating L'\0' in
   DEST.  */
extern wchar_t *wcpcpy (wchar_t *__restrict __dest,
            __const wchar_t *__restrict __src) __THROW;

/* Copy no more than N characters of SRC to DEST, returning the address of
   the last character written into DEST.  */
extern wchar_t *wcpncpy (wchar_t *__restrict __dest,
             __const wchar_t *__restrict __src, size_t __n)
     __THROW;
#endif  /* use GNU */


/* Wide character I/O functions.  */

#ifdef  __USE_XOPEN2K8
/* Like OPEN_MEMSTREAM, but the stream is wide oriented and produces
   a wide character string.  */
extern __FILE *open_wmemstream (wchar_t **__bufloc, size_t *__sizeloc) __THROW;
#endif

#if defined __USE_ISOC95 || defined __USE_UNIX98
__BEGIN_NAMESPACE_STD

/* Select orientation for stream.  */
extern int fwide (__FILE *__fp, int __mode) __THROW;


/* Write formatted output to STREAM.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int fwprintf (__FILE *__restrict __stream,
             __const wchar_t *__restrict __format, ...)
     /* __attribute__ ((__format__ (__wprintf__, 2, 3))) */;
/* Write formatted output to stdout.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int wprintf (__const wchar_t *__restrict __format, ...)
     /* __attribute__ ((__format__ (__wprintf__, 1, 2))) */;
/* Write formatted output of at most N characters to S.  */
extern int swprintf (wchar_t *__restrict __s, size_t __n,
             __const wchar_t *__restrict __format, ...)
     __THROW /* __attribute__ ((__format__ (__wprintf__, 3, 4))) */;

/* Write formatted output to S from argument list ARG.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int vfwprintf (__FILE *__restrict __s,
              __const wchar_t *__restrict __format,
              __gnuc_va_list __arg)
     /* __attribute__ ((__format__ (__wprintf__, 2, 0))) */;
/* Write formatted output to stdout from argument list ARG.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int vwprintf (__const wchar_t *__restrict __format,
             __gnuc_va_list __arg)
     /* __attribute__ ((__format__ (__wprintf__, 1, 0))) */;
/* Write formatted output of at most N character to S from argument
   list ARG.  */
extern int vswprintf (wchar_t *__restrict __s, size_t __n,
              __const wchar_t *__restrict __format,
              __gnuc_va_list __arg)
     __THROW /* __attribute__ ((__format__ (__wprintf__, 3, 0))) */;


/* Read formatted input from STREAM.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int fwscanf (__FILE *__restrict __stream,
            __const wchar_t *__restrict __format, ...)
     /* __attribute__ ((__format__ (__wscanf__, 2, 3))) */;
/* Read formatted input from stdin.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern int wscanf (__const wchar_t *__restrict __format, ...)
     /* __attribute__ ((__format__ (__wscanf__, 1, 2))) */;
/* Read formatted input from S.  */
extern int swscanf (__const wchar_t *__restrict __s,
            __const wchar_t *__restrict __format, ...)
     __THROW /* __attribute__ ((__format__ (__wscanf__, 2, 3))) */;

# if defined __USE_ISOC99 && !defined __USE_GNU \
     && (!defined __LDBL_COMPAT || !defined __REDIRECT) \
     && (defined __STRICT_ANSI__ || defined __USE_XOPEN2K)
#  ifdef __REDIRECT
/* For strict ISO C99 or POSIX compliance disallow %as, %aS and %a[
   GNU extension which conflicts with valid %a followed by letter
   s, S or [.  */
extern int __REDIRECT (fwscanf, (__FILE *__restrict __stream,
                 __const wchar_t *__restrict __format, ...),
               __isoc99_fwscanf)
     /* __attribute__ ((__format__ (__wscanf__, 2, 3))) */;
extern int __REDIRECT (wscanf, (__const wchar_t *__restrict __format, ...),
               __isoc99_wscanf)
     /* __attribute__ ((__format__ (__wscanf__, 1, 2))) */;
extern int __REDIRECT_NTH (swscanf, (__const wchar_t *__restrict __s,
                     __const wchar_t *__restrict __format,
                     ...), __isoc99_swscanf)
     /* __attribute__ ((__format__ (__wscanf__, 2, 3))) */;
#  else
extern int __isoc99_fwscanf (__FILE *__restrict __stream,
                 __const wchar_t *__restrict __format, ...);
extern int __isoc99_wscanf (__const wchar_t *__restrict __format, ...);
extern int __isoc99_swscanf (__const wchar_t *__restrict __s,
                 __const wchar_t *__restrict __format, ...)

没错,但是思路是一样的。使用的函数都是普通的 C 函数。只需使用 malloc 而不是 new,wcslen 而不是 wstring.length,将 string 更改为 char,wstring 更改为 wchar_t,然后在任何地方省略 .c_str(),你就拥有了普通的 C 代码。 - Stefan Steiger

1
正如我在评论中建议的那样,你应该看一下ICU。这是一个由IBM创建的跨平台C库,用于Unicode处理。它提供了对C++和Java的额外支持,并带有非常强大的String类。它被广泛应用于许多地方,如Android和iOS,因此非常稳定和成熟。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接