C语言中Linux下数据写入函数 fwrite 有关问题
C语言中Linux下数据写入函数 fwrite 问题
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
struct stu
{
char name[10];
int age;
};
main()
{
struct stu mystu[3];
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
int i;
strcpy(mystu[0].name,"Jim");
mystu[0].age=14;
strcpy(mystu[1].name,"Jam");
mystu[1].age=14;
strcpy(mystu[1].name,"Lily");
mystu[2].age=19;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
i=fwrite(mystu,sizeof(mystu),3,fp);
printf("%d bit was written.\n",i);
close(fp);
}
运行环境为ubuntu11.04 .运行没问题出现。但打开文件后是乱码,这是什么原因?
------解决方案--------------------
第一处:strcpy(mystu[2].name,"Lily");
第二处: i = fwrite(&mystu, sizeof(mystu), 1, fp);
楼主先查查fwirte的参数和返回值具体含义。
第三处:fclose(fp); close关闭的是文件描述符,fclose关闭的是文件指针。
楼主要留意Warning,Warning背后可能是一个error。
------解决方案--------------------
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
------解决方案--------------------
楼上眼力真好!……
手动打开文件确实显示的是乱码,如果你用程序打开并读出,就不是乱码了
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
struct stu
{
char name[10];
int age;
};
main()
{
struct stu mystu[3];
FILE * fp;
extern int errno;
char file[]="/root/a1.txt";
int i;
strcpy(mystu[0].name,"Jim");
mystu[0].age=14;
strcpy(mystu[1].name,"Jam");
mystu[1].age=14;
strcpy(mystu[1].name,"Lily");
mystu[2].age=19;
fp=fopen(file,"a+");
if(fp==NULL)
{
printf("cant't open file %s.\n",file);
printf("errno:%d\n",errno);
printf("ERR :%s\n",strerror(errno));
return;
}
else
{
printf("%s was opened.\n",file);
}
i=fwrite(mystu,sizeof(mystu),3,fp);
printf("%d bit was written.\n",i);
close(fp);
}
运行环境为ubuntu11.04 .运行没问题出现。但打开文件后是乱码,这是什么原因?
------解决方案--------------------
第一处:strcpy(mystu[2].name,"Lily");
第二处: i = fwrite(&mystu, sizeof(mystu), 1, fp);
楼主先查查fwirte的参数和返回值具体含义。
第三处:fclose(fp); close关闭的是文件描述符,fclose关闭的是文件指针。
楼主要留意Warning,Warning背后可能是一个error。
------解决方案--------------------
不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待
和
fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了
------解决方案--------------------
楼上眼力真好!……
手动打开文件确实显示的是乱码,如果你用程序打开并读出,就不是乱码了