您的位置:首页 > 编程语言 > C语言/C++

C语言文件输入输出读取中文TXT文件出现乱码

2018-03-17 19:18 281 查看
今天在实现一个倒序输出文件的程序时测试了英文数字和中文,唯独中文出现了乱码,源码如下
//倒序显示文件的内容
#include<stdio.h>
#include<stdlib.h>
#define CNTL_Z '\032'   //文件结尾标记
#define SLEN 81
int main()
{
char file[SLEN];
char ch;
FILE *fp;
long count,last;

puts("Enter the name of the file to be processed:");
scanf("%80s",file);
if((fp=fopen(file,"rb"))==NULL)
{
printf("reverse can't open %s\n",file);
exit(EXIT_FALLURE);
}
fseek(fp,0L,SEEK_END);  //定位到文件末尾
last=ftell(fp);
for(count=1L;count<=last;count++)
{
fseek(fp,-count,SEEK_END);
ch=getc(fp);
if(ch!=CNTL_Z && ch!='\r')
putchar(ch);
}
putchar('\n');
fclose(fp);
return 0;
}

如果明白原理其实很简单,汉字ANSI编码一个汉字对应两个字节,但是传统char类型只有一个字节,即putchar()只能输出汉字的一半,也就变成乱码了。下面的代码很好理解了
int main()
{
FILE *p;
char file[50];
scanf("%80s", file);
p = fopen(file, "r");
int i = 0;
char a[1000];
while ((a[i] = fgetc(p)) != EOF)
i++;
a[i] = '\0';
puts(a);
printf("\n\n");
for (int j = 0; j <= i - 1; j++)
printf("%c   ", a[j]);
system("pause");
return 0;
}

第一次输出是正常的,而第二次输出就是乱码至于怎么解决,把汉字看做字符串就可以了,或者两个字节一输出

如果你们有更好的想法,请留言告诉我
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: