C语言API读写文件

来源:互联网 发布:澳洲阳光海岸大学 知乎 编辑:程序博客网 时间:2024/05/21 06:30

只说写结构体。。

fopen fwrite fread,fseek,ftell, fclose; 常用这几个。

我发现写vector容器 能写,就是读出来不知道怎么读,好像结构体里面最好不要用c++ 的string, 这个能读也能写,就是析构的时候有异常。 学识浅薄,还不知道原因。

//////////////////struct

struct MYPLANTIME{
 char ip[20];
 bool bWeek[WEEK_NUM];
 COleDateTime time[TIME_NUM];
 MYPLANTIME()
 {
  for(int i = 0;i < WEEK_NUM;++i)
  {
   bWeek[i] = false;
  }
  for(int i = 0; i < TIME_NUM;++i)
  {
   time[i] = COleDateTime::GetCurrentTime();
  }
  strcpy(ip,"");
 }
};

/////////////////////

class CMyConfig
{
public:

 CMyConfig(void)
 {
 }

 ~CMyConfig(void)
 {
 }

 int GetPlanTime( vector<MYPLANTIME> &vec)
 {
  CString strPath = GetCurrentPath();
  strPath.Append(CA2W(PLAN_PATH));

  FILE *f = fopen(CW2A(strPath.GetBuffer()),"rb");
  int num = 0;
  if(f)
  {
   fseek(f,0,SEEK_END);
   long len = ftell(f);
   num = len / sizeof(MYPLANTIME);
   MYPLANTIME plan;
   fseek(f,0,SEEK_SET);
   for(int i = 0; i < num;++i)
   {
    fread(&plan,sizeof(plan),1,f);
    vec.push_back(plan);
   }
   fclose(f);
   f = 0;
  }
  return 0;
 }

 int SavePlanTime( vector<MYPLANTIME> plan)
 {   
  CString strPath = GetCurrentPath();
  strPath.Append(CA2W(PLAN_PATH));
  FILE *f = fopen(CW2A(strPath.GetBuffer()),"wb");
  if(f)
  {
   for(int i = 0; i < plan.size(); ++i)
   {
    fwrite(&plan[i],sizeof(MYPLANTIME),1,f);
   }
   fclose(f);
  }
  return 0;
 }
};

0 0
原创粉丝点击