文件题C语言
有如下结构体及变量定义:struct student
{
int num;
char name;
char sex;
int age;
};
struct student str={{10101,"LiLin",'M',18},{10102,"Zhan Fun",'M',19
},{10104,"Wang Min",'F',20}},s;
将文件内容写入磁盘文件 std.txt 中并存盘,再次打开文件,将最后一个数组元素的信息读入到变量s中,输出s的每个成员信息,每条信息输出后换行.
我的代码:
#include <stdio.h>
struct student
{
int num;
char name;
char sex;
int age;
};
int main()
{
struct student str={{10101,"LiLin",'M',18},{10102,"Zhan Fun",'M',19
},{10104,"Wang Min",'F',20}},s;
FILE *fp;
fp=fopen("std.txt","wb");
fwrite((char*)str,sizeof(struct student),3,fp);
fclose(fp);
return 0;
}
求助怎么用C语言实现啊?
我写了写入std.txt的代码,wb,w的方式都试过了,然后结果打开txt之后是乱码。。
难道不应该是乱码吗? 本帖最后由 零的执行人 于 2020-6-5 21:34 编辑
永恒的蓝色梦想 发表于 2020-6-5 19:48
难道不应该是乱码吗?
u'LiLin M v'Zhan Fun M x'Wang Min F
这样的...
确实能打印出来正确的数据,先就这样吧,估计用fprintf会好??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int num;
char name;
char sex;
int age;
};
int main()
{
struct student str={{10101,"LiLin",'M',18},{10102,"Zhan Fun",'M',19
},{10104,"Wang Min",'F',20}},s;
FILE *fp;
fp=fopen("std.txt","wb");
fwrite((char*)str,sizeof(struct student),3,fp);
fclose(fp);
FILE *fin2;
fin2=fopen("std.txt","rb");
fread((char*)str,sizeof(struct student), 3, fin2);
strcpy(s.name,"Wang Min");
//strcpy(s.sex ,'F');
s.sex ='F';
s.age =20;
s.num =10104;
fclose(fin2);
printf("%d\n%s\n%c\n%d\n",s.num ,s.name ,s.sex ,s.age );
return 0;
}
大佬是这样不,过目过目
页:
[1]