将结构体内容写入到文件中
#include<stdio.h>
#include<string.h>
struct student
{
char name[100];
int age;
};
int main()
{
struct student st = {"wangqinghe",30};
FILE * p = fopen("./c.txt","wb");
fwrite(&st,sizeof(st),1,p);
fclose(p);
return 0;
}
写入到文件中,文件大小是104b,(struct类的大小),多余的未填充的字段会是乱码。
会将整个结构大小和内容写入。
#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[100];
int age;
};
int main()
{
struct student st = {0};
FILE *p = fopen("./c.txt","rb");
fread(&st,sizeof(st),1,p);
fclose(p);
printf("name = %s, age = %d\n",st.name,st.age);
return 0;
}
运行结果:
exbot@ubuntu:~/wangqinghe/C/20190723$ gcc readWrite.c -o readWrite
exbot@ubuntu:~/wangqinghe/C/20190723$ ./readWrite
name = wangqinghe, age = 30
转载于:https://www.cnblogs.com/wanghao-boke/p/11240352.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)