C程序中如何从文本文件中读取数据到结构体中?
C程序中如何从文本文件中读取数据到结构体中?例如:structstu{inta;intb;}structstuss[3];文本文件中的数据:1,22,43,5我用frea...
C程序中如何从文本文件中读取数据到结构体中? 例如:struct stu{ int a; int b;} struct stu ss[3]; 文本文件中的数据: 1,2 2,4 3,5 我用fread函数读出来的全是0,请高手帮忙,谢谢!
展开
1个回答
展开全部
void
writefile(tree
t)
{
FILE
*fp;
if
(t
==
NULL)
{
return;
}
if
((fp
=
fopen(FILENAME,
"wb"))
==
NULL)
{
printf("can't
open
file
%s\n",
FILENAME);
return;
}
preorder(t,
fp);
fclose(fp);
}
tree
readfile(tree
t)
{
TSTUDENT
r_new;
FILE
*fp;
if
((fp
=
fopen(FILENAME,
"rb"))
!=
NULL)
{
printf("
======Read
from
this
file,
Please
wait...=====\n");
while(fread(&r_new,
sizeof(TSTUDENT),
1,
fp)
==
1)
{
inn
=
(PSTUDENT)malloc(sizeof(TSTUDENT));
*inn
=
r_new;
t
=
insert(defaultIndex,
t);
}
fclose(fp);
}
return
t;
}
/*
关键之处是要注意使用二进制文件,文本文件可能会忽略掉某些字符,导致读取失败,或读到的全是乱码*/
writefile(tree
t)
{
FILE
*fp;
if
(t
==
NULL)
{
return;
}
if
((fp
=
fopen(FILENAME,
"wb"))
==
NULL)
{
printf("can't
open
file
%s\n",
FILENAME);
return;
}
preorder(t,
fp);
fclose(fp);
}
tree
readfile(tree
t)
{
TSTUDENT
r_new;
FILE
*fp;
if
((fp
=
fopen(FILENAME,
"rb"))
!=
NULL)
{
printf("
======Read
from
this
file,
Please
wait...=====\n");
while(fread(&r_new,
sizeof(TSTUDENT),
1,
fp)
==
1)
{
inn
=
(PSTUDENT)malloc(sizeof(TSTUDENT));
*inn
=
r_new;
t
=
insert(defaultIndex,
t);
}
fclose(fp);
}
return
t;
}
/*
关键之处是要注意使用二进制文件,文本文件可能会忽略掉某些字符,导致读取失败,或读到的全是乱码*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询