用C语言编写文件为什么文件里是乱码?

#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[26];
FILE *fp;
if((fp=fopen("字符串.dat","w"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
gets(str);
fwrite(str,1,27,fp);
fclose(fp);
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
fread(str,1,26,fp);
printf("%s\n",str);
fclose(fp);
return 0;
}

输入a----z 26个字母文件里显示的是正确的,但是用
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char str[26];
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
fwrite(str,1,26,fp);fputs("\n",fp);
printf("%s\n",str);
fclose(fp);
return 0;
}
读取时读出的却是乱码,小弟是菜鸟,请教各位大侠!!!

第一个程序:
1. 你是想输入26个字母吧,那缓冲区长度不够,结尾要预留一个'\0'字符,char str[26] 至少要改成 char str[27]
2. 将字符输入文件时,不要写最后一个字符'\0', fwrite(str,1,27,fp) 改为 fwrite(str,1,26,fp); 原因是,文本文件当中是无须'\0'的,可能会导致乱码
3 字符读出来了之后,也要加上 str[26] = '\0' 语句

第二个程序:
1. 缓冲区不够, char str[26], 改为 char str[27]
2. 读取文件函数写错鸟,fwrite 改为 fread; 不要搞 fputs 了,文件是以"r"只读模式打开的
3 假使你把字符读出来了,也要加上 str[26] = '\0' 语句

#include<stdio.h>
#include<stdlib.h>
int main()
{
char str[100];
FILE *fp;
if((fp=fopen("字符串.dat","w"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
gets(str);
fwrite(str,1,26,fp);
fclose(fp);
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
fread(str,1,26,fp);
str[26] = '\0';
printf("%s\n",str);
fclose(fp);
return 0;
}

#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char str[100];
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
fread(str,1,26,fp);
str[26]='\0';
printf("%s\n",str);
fclose(fp);
return 0;
}追问

我把所有的26改为27
这样就不会出现缓冲区不够的问题了,也省去了str[26]='\0'
可以么?

追答

不能省去str[26]='\0', 特别是第二个程序,缓冲区没有初始化,要是刚好 str[26] 不是 ‘\0’ ,字符串就没有结尾,后面跟着一堆乱码(当然,debug版本的VS会自动初始化倒是看不出来)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-06-10
char str[26];
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");exit(0);
}
fwrite(str,1,26,fp);fputs("\n",fp);
str的初值在哪呢,你要写什麽进去呢,可不就是乱码了

你到底是读还是写fopen("字符串.dat","r") 以读方式打开
后面又是写fwrite(str,1,26,fp);fputs("\n",fp);追问

后面应该是fread,这个没太注意,str不是在输入的时候给了字符串了么?可不可以不初始化啊?

追答

改成fread我这读出来的就不是乱码了

第2个回答  2011-06-10
abcdefghijklmnopqrstuvwxyz
Press any key to continue

#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp;
char str[27]={0}; // 问题 一 长度不够 问题二 没有初始化
if((fp=fopen("字符串.dat","r"))==NULL)
{
printf("can't find the file!\n");
exit(0);
}
fread(str,1,27,fp); //问题三 是fread 不是 fwrite 问题四 注意长度 27
printf("%s\n",str);
fclose(fp);
return 0;
}追问

为什么要是27呢?

追答

结束符 系统自动给加上的

追问

也就是说从文件读入到内存中要比从内存写入到文件要多一个字节喽?

追答

是的

fread(str,1,28,fp);
len=sizeof(str);
printf("%d\n",len);

出来就是27

第3个回答  2011-06-10
//后一个程序的
fwrite(str,1,26,fp);fputs("\n",fp); //这是写,不是读。
//改为
fread(str,1,26,fp);fputs("\n",fp);追问

谢谢提醒,我改了,但是输出最后还是有乱码的,请教!!!

追答

1 你第一个程序输入的时候字符数少点;
2 将fread(str,1,26,fp);fputs("\n",fp);中的26改为27。

相似回答