/* 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;
}