2011-10-09 47 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应该已经和您需要的一样大。