首页 > 代码库 > 保存结构体到文件

保存结构体到文件

经常有这样一种需求,希望有些设置的信息(比如说账号信息)能够掉电后不丢失,重新开机后能够重新读出来。最简单的做法是把信息保存在文件中,文件在nand flash上就不会掉电丢失。

我们不仅可以向文件中写字符串,其实写结构体也是可以的。注意结构体里面不能有指针。

假设我们要保存一个账号结构体到文件,

#include <stdio.h>
#include <errno.h>
#include <string.h>
typedef struct _Account{
  char usrname[128];
  char passwd[128];
  int age;
  int level;
}Account;
void write_account2file(const char *path, Account *account)
{
  FILE *fp = NULL;
  fp = fopen(path, "w+");
  if (NULL == fp)
  {
    printf("open %s fail, errno: %d", path, errno);
    return;
  }
  fwrite(account, sizeof(Account), 1, fp);
  fclose(fp);
  return;
}

void read_accountFromFile(const char *path, Account *account)
{
  FILE *fp = fopen(path, "r");
  if (NULL == fp)
  {
    printf("open %s fail, errno: %d", path, errno);
    return;
  }
  fread(account, sizeof(Account), 1, fp);
  fclose(fp);
}


void main(void)
{
  #if 0
  Account account;
  strncpy(account.usrname, "fellow", strlen("fellow"));
  account.usrname[strlen("fellow")] = ‘\0‘;
  strncpy(account.passwd, "1111", strlen("1111"));
  account.passwd[strlen("1111")] = ‘\0‘;
  account.age = 18;
  account.level = 0;
  write_account2file("/mnt/hgfs/share/test/account.txt", &account);
  #endif
  Account read;
  read_accountFromFile("/mnt/hgfs/share/test/account.txt", &read);
  printf("read:%s,%s,%d,%d\n", read.usrname, read.passwd, read.age,read.level);

}

执行结果如下:

技术分享

 

保存结构体到文件