关于C中读取文件的问题
我首先把一个结构写入到文件中,然后从文件中读取这个结构,如下:
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编译器
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编译器
...全文
相关推荐
C 代码 读取城市到城市距离的文件并求解一个小 旅行销售员问题 (TSP).rar
标题中的"C代码 读取城市到城市距离的文件并求解一个小旅行销售员问题(TSP)"指的是一项编程任务,它使用C语言来解决经典的图论问题——旅行销售员问题(Traveling Salesman Problem
C语言实现从文件中读取数据
在C语言中,读取文件数据是编程过程中常见的任务,特别是在处理输入/输出操作时。本文将深入探讨如何使用C语言来实现从文件中读取数据。
用ACO解决TSP问题,数据为Solomon数据集的c101文件读取,可视化路径图,用图展示每次迭代的最优值、最差值和平均值
**初始化阶段**: - **城市坐标**:从c101文件中读取城市坐标(x和y坐标),用`distance_x`和`distance_y`列表存储。
C语言解决n皇后问题 例如八皇后问题 列出所有解的情况
使用C语言的`fopen`, `fscanf`, `fclose`等函数可以实现文件读取。
用C语言读取汉字库文件,找出汉字信息的示例!
总的来说,用C语言读取汉字库文件是一项涉及文件I/O、二进制数据解析和内存管理的复杂任务。理解和处理.FON文件需要深入理解文件格式,同时遵循良好的编程实践以避免潜在的问题,如内存泄漏和错误处理。


