用C语言实现。把结构体写入文件,然后再读取出来并显示;
/* structinfile .c
* Auther: tweety
* date:
*/
#include
typedef struct Filenode
{
int isempty;
char * data;
}filenode;
int node_init(filenode *node)
{
node->isempty=1;
node->data = "FOOLisENOUGH!";
return 0;
}
int node_write_infile(filenode * node)
{
//把结构体写入文件
FILE *fp=fopen("file.txt","w");
if(fwrite(node,sizeof(Filenode),1,fp))
{
fclose(fp);
return 1;
}
else return 0;
}
int node_read_outfile(filenode *node)
{
//读取结构体
FILE *fp =fopen("file.txt","r");
if(fread(node,sizeof(Filenode),1,fp))
{
fclose(fp);
return 1;
}
else return 0;
}
int main()
{
filenode *innode = malloc(sizeof(filenode));
filenode *outnode =malloc(sizeof(filenode));
node_init(innode);
if(node_write_infile(innode)) printf("file write OK\n");
if(node_read_outfile(outnode))
{
printf("%d\n",outnode->isempty);
printf("%s\n",outnode->data);
}
system("pause");
return 0;
}