zoukankan      html  css  js  c++  java
  • 保存结构体到文件

    经常有这样一种需求,希望有些设置的信息(比如说账号信息)能够掉电后不丢失,重新开机后能够重新读出来。最简单的做法是把信息保存在文件中,文件在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")] = '';
      strncpy(account.passwd, "1111", strlen("1111"));
      account.passwd[strlen("1111")] = '';
      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 ", read.usrname, read.passwd, read.age,read.level);

    }

    执行结果如下:

  • 相关阅读:
    hdu3874
    spoj D-query
    hdu4348
    hdu4417
    hdu2665
    [LUOGU] P1057 传球游戏
    [CODEVS] 2193 数字三角形WW
    [CODEVS] 2189 数字三角形W
    [模板] 线段树
    [模板] 树状数组
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6142767.html
Copyright © 2011-2022 走看看