我正在尝试将带有char *字符串的结构保存到文件中.
struct d_object {
int flags;
int time;
int offset;
char *filename;
};
问题是,当我这样做时,我显然只会保存该指针的地址而不是字符串.所以我所做的只是使用一个字符数组,但我不得不设置字符串的最大大小.这工作正常,但我想知道是否有任何存储结构与文件中的char *(我在某些时候malloc)然后检索它.我可以保存字符串和结构分开,然后检索它们,但它是相当混乱.如果我可以将整个结构(上面的结构)加载并保存到文件中,那将是更好的选择.谢谢!
带有char数组的代码如下:
#include
#include
#include
struct d_object {
int flags;
int time;
int offset;
char filename[255];
};
int main(int argc, char **argv) {
struct d_object fcb;
fcb.flags=5;
fcb.time=100000;
fcb.offset=220;
strncpy(fcb.filename,"myfile",255);
int fd=open("testfile",O_RDWR);
write(fd,&fcb,sizeof(fcb));
close(fd);
int fd2 = open("testfile",O_RDONLY);
struct d_object new_fcb;
read(fd2,&new_fcb,sizeof(new_fcb));
printf("read from file testfile: %s\n",new_fcb.filename);
return 0;
}
P.S.:我没有使用STREAM函数,因为这实际上是指在没有它们的嵌入式操作系统上运行.我刚刚调整了* BSD / Linux的代码,所以在提问时更有意义.