写指针在C文件 [英] Write pointer to file in C

查看:136
本文介绍了写指针在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个stucture:

I have a stucture:

typedef struct student {
  char *name;
  char *surname;
  int age;
} Student;

我需要将它写入二进制文件。

I need to write it to binary file.

Student *s = malloc(sizeof(*s));

我填写我的结构数据,然后我写的文件:

I fill my structure with data and then i write in to the file:

fwrite(s, sizeof(*s), 1, fp);

在我的文件犯规存在的姓名,它具有char类型的不会忽略*。
我为什么能写入文件的Word,而不是一个不会忽略?

In my file doesnt exist a name and surname, it have an adresses of char*. How can i write to file a word, not an adresses?

推荐答案

您需要取消引用指针和写结构的各个部分。 (你不应该直接使用fwrite一个结构,而是连接code及其零部件和写那些:

You need to dereference your pointer and write the parts of the struct. (You should not fwrite a struct directly, but rather encode its parts and write those:

Student *s = malloc(sizeof(*s));
s->name = "Jon";
s->surname = "Skeet";
s->age = 34;

// ....

fwrite(s->name, sizeof(char), strlen(s->name) + 1, fp);
fwrite(s->surname, sizeof(char), strlen(s->surname) + 1, fp);

//This one is a bit dangerous, but you get the idea.
fwrite(&(s->age), sizeof(s->age), 1, fp); 

这篇关于写指针在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆