La mia configurazione: gcc-4.9.2, ambiente UTF-8.Come utilizzare UTF-8 nel codice C?
Il seguente programma C funziona in ASCII, ma non in UTF-8.
Crea file di input:
echo -n 'привет мир' > /tmp/вход
Questo è test.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
int main(void)
{
char buf[SIZE+1];
char *pat = "привет мир";
char str[SIZE+2];
FILE *f1;
FILE *f2;
f1 = fopen("/tmp/вход","r");
f2 = fopen("/tmp/выход","w");
if (fread(buf, 1, SIZE, f1) > 0) {
buf[SIZE] = 0;
if (strncmp(buf, pat, SIZE) == 0) {
sprintf(str, "% 11s\n", buf);
fwrite(str, 1, SIZE+2, f2);
}
}
fclose(f1);
fclose(f2);
exit(0);
}
controllare il risultato:
./test; grep -q ' привет мир' /tmp/выход && echo OK
Cosa si deve fare per far funzionare UTF-8 codice come se fosse un codice ASCII - non preoccuparsi di quanti byte un simbolo prende, ecc. In altre parole: cosa cambiare nell'esempio per trattare un y Simbolo UTF-8 come singola unità (che include argv, STDIN, STDOUT, STDERR, input di file, output e il codice del programma)?
Check link http://www.nubaria.com/en/blog/?p=289 – Razib
vostro 'modello grep' ha uno spazio iniziale . – tripleee
Inoltre, non dare un nome al 'test' dei programmi, poiché questo è un built-in di shell. ('./test' funziona, naturalmente, ma è un'abitudine che non vuoi mantenere.) – tripleee