2011-10-09 98 views
3

使用「opendir」和「readdir」我讀取目錄內容。 在這個過程中我做一些字符串操作/配置: 類似的東西:utf8字符串和c中的malloc

int stringlength = strlen(cur_dir)+strlen(ep->d_name)+2; 
char *file_with_path = xmalloc(stringlength); //xmalloc is a malloc wrapper with some tests (like no more memory) 
snprintf (file_with_path, (size_t)stringlength, "%s/%s", cur_dir, ep->d_name); 

但是,如果一個字符串包含兩個字節的字符UTF8? 你如何處理這個問題?

stringlength*2? 

感謝

回答

8

strlen()計數字符串中的字節數,如果包含字節代表UTF-8編碼的Unicode字符,它並不關心。因此,例如,包含UTF-8編碼「aöü」的字符串的strlen()將返回5,因爲該字符串編碼爲"a\xc3\xb6\xc3\xbc"

+1

爲了完整起見,可能值得指出的是,UTF-8編碼的字符串永遠不會包含值爲0的字節,即它仍然是C的字符串函數視角的有效字符串,雖然它們會計數字節作爲字符。 – unwind

+0

咦?當然,UTF-8編碼的C字符串不會包含NUL字節。但是這並沒有說明UTF-8。 –

+0

@Per:UTF-8通常不包含NUL字節,編碼就是這樣做的。 – sth

2

strlen統計字符串中的字節數(直到終止NUL),而不是UTF-8字符的數量,所以stringlength應該已經和您需要的一樣大。