2013-03-15 95 views
2

我使用GCC和Mac OS X從vswprintf中得到莫名其妙的失敗(返回值爲-1)(在Mac OS X 10.6和10.8下使用gcc 4.0和4.2.1測試)GCC在Linux下是不是受影響.Visual Studio也是不是受影響)。vswprintf在Mac OS X下某些unicode codepoints失敗

爲了證明我有最低限度從here適配,使得它打印出vswprintf的返回值的例子問題:

/* vswprintf example */ 
#include <stdio.h> 
#include <stdarg.h> 
#include <wchar.h> 

void PrintWide (const wchar_t * format, ...) 
{ 
    wchar_t buffer[256]; 
    va_list args; 
    va_start (args, format); 
    int res = vswprintf (buffer, 256, format, args); 
    wprintf (L"result=%d\n", res); 
    fputws (buffer, stdout); 
    va_end (args); 
} 

int main() 
{ 
    wchar_t str[] = L"test string has %d wide characters.\n"; 
    PrintWide (str, wcslen(str)); 
    return 0; 
} 

從我的測試看來,取決於str值,vswprintf會有時會失敗。例子:

wchar_t str[] = L"test string has %d wide characters.\n"; // works 
wchar_t str[] = L"ßß® test string has %d wide characters.\n"; // works 
wchar_t str[] = L"日本語 test string has %d wide characters.\n"; // FAILS 
wchar_t str[] = L"Π test string has %d wide characters.\n"; // FAILS 
wchar_t str[] = L"\u03A0 test string has %d wide characters.\n"; // FAILS 

看來,包括與Unicode代碼點以上0xff字符的任意字符串將觸發此問題。任何人都可以闡明爲什麼會發生這種情況?這似乎是一個太大的問題,以前沒有注意到!

+0

請問您的源文件的編碼匹配有望在字符串編碼? – Dmitri 2013-03-15 18:03:31

+0

我希望'fputws'調用在缺省''C「'語言環境中對超出範圍字符失敗,但'vswprintf'應該可以工作。 – 2013-03-15 23:41:48

+0

標題中沒有「GCC vswprintf」。在Mac OS X上,GCC在GNU/Linux上的表現與GCC有所不同,原因是'vswprintf'與GCC無關,它是由操作系統的C庫'libc'提供的 – 2013-03-17 17:50:50

回答

0

如果你設置的語言環境,它應該沒問題。要拿起環境變量,你可以這樣做:

setlocale(LC_CTYPE, ""); // include <locale.h> 

或者明確設置它。這是因爲所有的輸出函數都需要知道使用哪種編碼。

OS X根本沒有執行vswprintf,而Linux運行它(儘管打印時字符會不正確)。

下面是glibc的文檔的相關章節:

If the format string contains non-ASCII wide characters, the program 
    will only work correctly if the LC_CTYPE category of the current locale 
    at run time is the same as the LC_CTYPE category of the current locale 
    at compile time. This is because the wchar_t representation is plat‐ 
    form- and locale-dependent. (The glibc represents wide characters 
    using their Unicode (ISO-10646) code point, but other platforms don't 
    do this. 
+0

實際上,IMO'vswprintf'調用不應該受locale影響,但'fputsw'調用應該會失敗... – 2013-03-15 23:42:47

+0

你確實是對的!順便說一句,在Ubuntu 11.04下,調用不僅成功,而且即使沒有設置語言環境,輸出也是正確的。 – Xaxx 2013-03-21 12:55:58

+0

@Xaxx - 很高興幫助。我認爲Ubuntu 11.04必須更加寬容。我在Ubuntu 12.10中嘗試過,它給了錯誤的字符(手冊頁說LC_CTYPE必須設置)。 – teppic 2013-03-21 12:57:37