关于C中读取文件的问题

youhaodeyi 2007-12-06 01:24:37
我首先把一个结构写入到文件中,然后从文件中读取这个结构,如下:
1 #include "malloc.h"
2 #include "stdio.h"
3 typedef struct {
4 int numberint;
5 double numberdouble;
6 }Type;
7
8 int main()
9 {
10 FILE *file;
11 Type *t,*r;
12
13
14 t=(Type*)malloc(sizeof(Type));
15 t->numberint=10;
16 t->numberdouble=10.3838;
17
18 file=fopen("test.txt","w+");
19 if(file != NULL){
20 fwrite((const void*)(t),sizeof(Type),1,file);
21 close(file);
22 }
23
24 file=fopen("test.txt","r");
25 r = (Type*)malloc(sizeof(Type));
26 if(file!=NULL){
27 fread(r,sizeof(Type),1,file);
28 close(file);
29 printf("int:%d\n",r->numberint);
30 printf("double:%lf\n",r->numberdouble);
31 }
32 }

但是输出都是0,这是为什么?我在linux上运行,用的是gcc编译器
...全文
103 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
chlaws 2007-12-06
  • 打赏
  • 举报
回复

//主要是你关闭文件出错了。不是close() 而是fclose()
#include "malloc.h"
#include "stdio.h"
typedef struct {
int numberint;
double numberdouble;
}Type;

int main()
{
FILE *file;
Type *t,*r;


t=(Type*)malloc(sizeof(Type));
t-> numberint=10;
t-> numberdouble=10.3838;

file=fopen("test.txt","w+");
if(file != NULL){
fwrite((const void*)(t),sizeof(Type),1,file);
fclose(file);
}

file=fopen("test.txt","r");
r = (Type*)malloc(sizeof(Type));
if(file!=NULL){
fread(r,sizeof(Type),1,file);
fclose(file);
printf("int:%d\n",r-> numberint);
printf("double:%lf\n",r-> numberdouble);
}
}


chlaws 2007-12-06
  • 打赏
  • 举报
回复
哦错了,fclose(file); 不是close(file)
chlaws 2007-12-06
  • 打赏
  • 举报
回复

//直接在你基础上改下,你试下可不可以的,我没在编译器上试。不行的话再改
1 #include "malloc.h"
2 #include "stdio.h"
3 typedef struct {
4 int numberint;
5 double numberdouble;
6 }Type;
7
8 int main()
9 {
10 FILE *file;
11 Type *t,*r;
12
13
14 t=(Type*)malloc(sizeof(Type));
15 t-> numberint=10;
16 t-> numberdouble=10.3838;
17
18 file=fopen("test.txt","w+");
19 if(feof(file)==0){
20 fwrite((const void*)(t),sizeof(Type),1,file);
21
22 } close(file);
23
24 file=fopen("test.txt","r");
25 r = (Type*)malloc(sizeof(Type));
26 if(feof(file)==0){
27 fread(r,sizeof(Type),1,file);
28
29 printf("int:%d\n",r-> numberint);
30 printf("double:%lf\n",r-> numberdouble);
31 } close(file);
32 }



69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧