将单字符串转换为C中的相应字符串

我需要将一个unicoded字符串转换为适当的语言。 我需要逐行读取文本文件。 有一条线可能包含一个像这样的unicode

\ XE6 \西飞\ 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  #include  #include  #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以hex解释的以下两个字节的值。

我能够完成转换。 以下是我的最终代码

  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 | sed \'s/[\\\\x]//g\' | xxd -r -p >> data.txt",str); printf("Final String: %s\nUnicode String Size: %ld\n",str2,strlen(str)); system(str2); } 

感谢您的所有回复,并感谢@chux为您的指针