如何在 C 中打印 UTF-8 字符串
How to print UTF-8 string in C
我有这个功能:
void read_request(int fd) {
int size = 50, pos = 0, b;
char* buffer = calloc(size, 1);
while (strncmp(buffer + (pos - 4 < 0 ? 0 : pos - 4), "\r\n\r\n", 4)) {
if ((b = read(fd, buffer + pos, size - pos)) == -1) {
perror("read() error");
exit(-1);
}
pos += b;
if (pos >= size) {
size *= 2;
buffer = realloc(buffer, size);
}
}
fwrite(buffer, 1, pos, stdout);
free(buffer);
}
它从浏览器请求中读取 HTTP headers 并打印出来。它工作正常,直到我将西里尔符号放入 URL,例如:http://127.0.0.1/тест
。所有 ASCII 符号将照常打印,但 тест
打印为十六进制值:
GET /%D1%82%D0%B5%D1%81%D1%82 HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
如何打印成普通可读文本?
%D1%82%D0%B5%D1%81%D1%82 被 url 编码。 Web 浏览器 url 在将 unicode 字符串发送到服务器之前对其进行编码。
我不确定如果你取消url编码你会看到什么。是否正确显示unicode可能取决于终端。
我有这个功能:
void read_request(int fd) {
int size = 50, pos = 0, b;
char* buffer = calloc(size, 1);
while (strncmp(buffer + (pos - 4 < 0 ? 0 : pos - 4), "\r\n\r\n", 4)) {
if ((b = read(fd, buffer + pos, size - pos)) == -1) {
perror("read() error");
exit(-1);
}
pos += b;
if (pos >= size) {
size *= 2;
buffer = realloc(buffer, size);
}
}
fwrite(buffer, 1, pos, stdout);
free(buffer);
}
它从浏览器请求中读取 HTTP headers 并打印出来。它工作正常,直到我将西里尔符号放入 URL,例如:http://127.0.0.1/тест
。所有 ASCII 符号将照常打印,但 тест
打印为十六进制值:
GET /%D1%82%D0%B5%D1%81%D1%82 HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
如何打印成普通可读文本?
%D1%82%D0%B5%D1%81%D1%82 被 url 编码。 Web 浏览器 url 在将 unicode 字符串发送到服务器之前对其进行编码。
我不确定如果你取消url编码你会看到什么。是否正确显示unicode可能取决于终端。