结构体存储文件,从文件中读取结构体

/* 2012 COPYRIGHT GPL */

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>

typedef enum{
    NORMAL,
    SILVER,
    GOLD
}Type;

typedef struct{
    int id;
    int money;
    Type type;
    char name[20];
}Card;

int fd = 0;

/* initialize card */
void init(Card *card)
{
    card->id = 0;
    card->money = 100;
    card->type = NORMAL;
    strcpy (card->name, "World travel card!");
}   

/* open a file */
int file_open(void)
{
    fd = open("./b.txt",O_RDWR);
    if (-1 == fd)
    {
        fprintf(stdout,"Open file error\n");
 return -1;
    }
    return 0;
   
}

/* read struct from file */
int file_read(Card* card)
{
    if ( (ssize_t )sizeof(Card) != read(fd,card,sizeof(Card)) )
    {
        return -1;
    }
    return 0;
}

/* write struct into file */
int file_write(Card *card)
{
    if ( (ssize_t)sizeof(Card) != write(fd,card,sizeof(Card)) )
    {
        fprintf(stdout,"Write file error\n");
 return -1;
    }
    return 0;
}

/* close file */
int file_close(void)
{
    if (-1 == close(fd))
    {
        return -1;
    }
    return 0;
}

/* print the content of card */
void  output(Card* card)
{
    fprintf(stdout,"card->id: %d,card->money: %d,card->type: %d,card->name: %s\n",\
                    card->id,card->money,card->type,card->name);
}

int main(int *argc[],char* argv[])
{
    /* 灏嗙粨鏋勪綋鍐欏叆鏂囦欢 */
    int fd = 0;
    Card card;
    init(&card);
    output(&card);
    if (-1 == file_open())
    {
        exit(-1);
    }
    if (-1 == file_write(&card))
    {
        exit(-1);
    }
    if ( -1 == file_close() )
    {
        exit(-1);
    }
   
    /* 浠庢枃浠朵腑璇诲嚭缁撴瀯浣擄紝璧嬪€兼柊鐨勭粨鏋勪綋 */
    Card card1;
    if (-1 == file_open())
    {
 exit(-1);
    }
    if (-1 == file_read(&card1))
    {
        exit(-1);
    }
    if ( -1 == file_close() )
    {
        exit(-1);
    }
    output(&card1);
    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值