首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用fwrite将结构数组写入二进制文件

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

Stack Overflow用户
提问于 2013-12-14 18:18:31
回答 1查看 9.3K关注 0票数 2

我有:

代码语言:javascript
复制
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);调用

但不会向文件中写入任何内容。有人能发现我的错误吗?我不知道该怎么做,我发现其他人的搜索要么没有联系,要么只是让我走了这么远。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-14 19:25:04

需要将FILE *作为参数传递,如下所示:

test.c

代码语言:javascript
复制
#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;
}

结果

代码语言:javascript
复制
$ ./test
$ ls -l points.txt 
-rw-r--r-- 1 me me 80 Dec 14 22:24 points.txt
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20582047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档