1. 以二进制方式读写结构体
struct
Student
{
string name;
string sex;
int
age;
}
void
write(string filePath,
const
struct
Student* stu,
int
n)
{
FILE
*fp;
int
i;
if
((fp=
fopen
(filePath,
"wb"
))==NULL)
{
printf
(
"cant open the file"
);
return
;
}
for
(i=0;i<n;i++)
{
if
(
fwrite
(&stu[i],
sizeof
(
struct
Student),1,fp)!=1)
printf
(
"file write error\n"
);
}
fclose
(fp);
}
void
read(string filePath,
const
struct
Student* stu,
int
n)
{
FILE
*fp;
int
i;
if
((fp=
fopen
(filePath,
"rb"
))==NULL)
{
printf
(
"cant open the file"
);
return
;
}
for
(i=0;i<n;i++)
{
if
(
fread
(&stu[i],
sizeof
(
struct
Student),1,fp)!=1)
printf
(
"file read error\n"
);
}
fclose
(fp);
}
|
本文转自静默虚空博客园博客,原文链接:http://www.cnblogs.com/jingmoxukong/articles/2132600.html,如需转载请自行联系原作者