我有:
pointfile = fopen("points.bin", "wb");
void savepoints(point points[], int n, FILE f){
fwrite(&points, sizeof(point), n, &f);
return;
}
fclose(pointfile);where typedef struct {float x; float y;} point;
并由savepoints(buffer, npoints, *pointfile);调用
但不会向文件中写入任何内容。有人能发现我的错误吗?我不知道该怎么做,我发现其他人的搜索要么没有联系,要么只是让我走了这么远。
发布于 2013-12-14 19:25:04
需要将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.txthttps://stackoverflow.com/questions/20582047
复制相似问题