我有:
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;} point;
并由savepoints(buffer, npoints, *pointfile);
但没有任何内容写入文件。谁能发现我的错误?我无法看到如何解决这个问题,而其他我发现搜索要么没有关联,要么只是让我这么远。
答案 0 :(得分:2)
需要传递FILE *
作为参数,如:
<强> test.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