我需要将 unicode 字符串转换为其适当的语言。我需要逐行读取文本文件。一行有可能包含像这样的 unicode
\xE6\xAC\xA2\xE8\xBF\x8E
这基本上是一个中文文本,等于
欢迎
现在我需要从文本文件中删除这一行(\xE6\xAC\xA2\xE8\xBF\x8E),将此unicode转换为中文文本,将此中文文本附加到文本文件中。
以下是我的 data.txt 文件的内容:
testing
programming
\xE6\xAC\xA2\xE8\xBF\x8E
development
我想获取文件内容为:
testing
programming
development
欢迎
以下是我到目前为止所做的事情
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 256
int main()
{
int ctr = 0;
char ch;
FILE *fptr1, *fptr2;
char fname[MAX] = "data.txt";
char str[MAX], temp[] = "temp.txt";
char str2[256];
fptr1 = fopen(fname, "r");
if (!fptr1)
{
printf(" File not found or unable to open the input file!!\n");
return 0;
}
fptr2 = fopen(temp, "w"); // open the temporary file in write mode
if (!fptr2)
{
printf("Unable to open a temporary file to write!!\n");
fclose(fptr1);
return 0;
}
// copy all contents to the temporary file except the specific line with unicode characters
while (!feof(fptr1))
{
strcpy(str, "\0");
fgets(str, MAX, fptr1);
if (!feof(fptr1))
{
ctr++;
if(strstr(str,"\\")!=NULL)
{
memset(str2,'\0',sizeof(str2));
printf("Input String Contains Unicode Character\n");
str[strlen(str)-1]='\0';
sprintf(str2,"echo %s >> data.txt",str);
printf("Final String: %s\nUnicode String Size: %ld\n",str2,strlen(str));
system(str2);
}
else
{
fprintf(fptr2, "%s", str);
}
}
}
fclose(fptr1);
fclose(fptr2);
remove(fname); // remove the original file
rename(temp, fname); // rename the temporary file to original name
/*------ Read the file ----------------*/
fptr1=fopen(fname,"r");
ch=fgetc(fptr1);
printf(" Now the content of the file %s is : \n",fname);
while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fptr1);
}
fclose(fptr1);
/*------- End of reading ---------------*/
return 0;
}
当尝试编译并运行此代码时,下面是我看到的输出
Input String Contains Unicode Character
Final String: echo \xE6\xAC\xA2\xE8\xBF\x8E >> data.txt
Unicode String Size: 24
Now the content of the file data.txt is :
testing
programming
development
xE6xACxA2xE8xBFx8E
更改以下行后的相同代码,它按预期工作
sprintf(str2,"echo %s >> data.txt",str);
sprintf(str2,"echo %s >> data.txt","\xE6\xAC\xA2\xE8\xBF\x8E");
但是当从文件中读取该值时,它不起作用。
同样这一行,字符串被识别为大小正确的 unicode 字符串
printf("Final String: %s\nUnicode String Size: %ld\n",str2,strlen(str));
The String Size: 6
有人可以告诉我,如何在从文本文件读取时将值转换为中文吗?
最佳答案
您必须识别行中的 \x
位置,例如指针 p
然后指向下一个字符。现在
char hex[3] = { p[0], p[1], 0 };
char val = strtoul(hex, 0, 16);
p += 2;
将返回 val
中以十六进制解释的以下两个字节的值。
关于将unicode字符串转换为C中对应的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48537793/