gpt4 book ai didi

c - 使用 fwrite 将结构数组写入二进制文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:39 30 4
gpt4 key购买 nike

我有:

pointfile = fopen("points.bin", "wb");
void savepoints(point points[], int n, FILE f){
fwrite(&points, sizeof(point), n, &f);
return;
}
fclose(pointfile);

其中 typedef struct {float x; float y;} 点;

并由 savepoints(buffer, npoints, *pointfile); 调用

但是没有任何内容写入文件。谁能发现我的错误?我看不出如何解决这个问题,我发现其他人的搜索要么不相关,要么只是让我走到这一步。

最佳答案

需要传递一个 FILE * 作为参数,例如:

测试.c

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
float x,
y;
}point;

/* function to save points data to myfile */
void save_points(point *points, int num_points, FILE *myfile)
{
/* have to use points not (&points) here */
fwrite(points, sizeof(point), num_points, myfile);
}

int main()
{
FILE *pointfile;
point *points; int num_points, index;
pointfile = fopen("points.txt", "w");
if(!pointfile)
{
fprintf(stderr, "failed to create file 'points.txt'\n");
goto err0;
}
num_points = 10;
points = malloc(num_points * sizeof(point));
if(!points)
{
fprintf(stderr, "failed to alloc `points`\n");
goto err1;
}
/* points are uninitialized but can still write uninitialized memory to file to test.. */
save_points(points, num_points, pointfile);
free(points);
fclose(pointfile);
return 0;

err1:
fclose(pointfile);
err0:
return 0;
}

结果

$ ./test
$ ls -l points.txt
-rw-r--r-- 1 me me 80 Dec 14 22:24 points.txt

关于c - 使用 fwrite 将结构数组写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582047/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com