我正在开发一个通过嵌入式设备与JavaScript和C进行通信的项目。我的目标是在由fOpen()创建的.BIN文件上保存和检索数据

但是,当我尝试运行代码时,存储的数据将被删除,然后附加新数据。请参见下面的代码:(注意:请忽略不必要的变量)

typedef struct datarec
{
  char name[50];
  char age[50];
  char salary [50];
  char position[50];
  char department[50];
}REC;

//Post the data on .BIN file
static int32 MODDECL fileDataSet(HANDLE* pCPU, void* pbase)
{
//This part just determines what variable from data struct will be updated
  char *fileName = vplStringGet(pCPU, data->fileName);
  char *GrpName = vplStringGet(pCPU, data->GrpName);
  char *IDName = vplStringGet(pCPU, data->IDName);
  char *newValue = vplStringGet(pCPU, data->newValue);

  FILE *f;
  REC r;
  f = fopen(fileName, "wb");

  if (f != NULL)
  {
    if (strcmp(IDName, "name") == 0)
    {
      strcpy(r.name, newValue);
      fwrite(&r,sizeof(r),1,f);
      fflush(stdin);
    }
    else if (strcmp(IDName, "age") == 0)
    {
      strcpy(r.age, newValue);
      fwrite(&r,sizeof(r),1,f);
      fflush(stdin);
    }
    else if (strcmp(IDName, "salary") == 0)
    {
      strcpy(r.salary, newValue);
      fwrite(&r,sizeof(r),1,f);
      fflush(stdin);
    }
    else if (strcmp(IDName, "position") == 0)
    {
      strcpy(r.position, newValue);
      fwrite(&r,sizeof(r),1,f);
      fflush(stdin);
    }
    else if (strcmp(IDName, "department") == 0)
    {
      strcpy(r.department, newValue);
      fwrite(&r,sizeof(r),1,f);
      fflush(stdin);
    }
    else
    {
      //Wrong ID
    }
  }
  else
  {
    //file not opened
  }
  fclose(f);
}

//This requests for the data stored at .BIN file and sends it to the device
static int32 MODDECL fileDataGet(HANDLE* pCPU, void* pbase)
{

  char strBuf[BUF_STRING_SIZE_VPL];
  char *fileName = vplStringGet(pCPU, data->fileName);
  char *GrpName = vplStringGet(pCPU, data->GrpName);
  char *IDName = vplStringGet(pCPU, data->IDName);

  FILE *f;
  REC r;
  f = fopen(fileName, "rb");
  if (f != NULL)
  {
    fread(&r,sizeof(r),1,f);
    if (strcmp(IDName, "name") == 0)
    {
      strncpy(strBuf, r.name, BUF_STRING_SIZE_VPL);
    }
    else if (strcmp(IDName, "age") == 0)
    {
      strncpy(strBuf, r.age, BUF_STRING_SIZE_VPL);
    }
    else if (strcmp(IDName, "salary") == 0)
    {
      strncpy(strBuf, r.salary, BUF_STRING_SIZE_VPL);
    }
    else if (strcmp(IDName, "position") == 0)
    {
      strncpy(strBuf, r.position, BUF_STRING_SIZE_VPL);
    }
    else if (strcmp(IDName, "department") == 0)
    {
      strncpy(strBuf, r.department, BUF_STRING_SIZE_VPL);
    }
    else
    {
      //Wrong ID
    }
  }
  else
  {
    //File not opened
  }
  fclose(f);
}


如果我只想更新特定的struct var,该怎么办?我不想删除/附加整个.bin文件。我只想更新需要更新的内容,然后直接访问它。谢谢

最佳答案

这里的主要问题是,每次对fileDataSet的调用都将创建一个新的未初始化的REC结构,该结构中的数据将是不确定的(看似随机或无用)。

要修改文件中的现有结构,您首先需要从文件中读取现有数据,修改结构,然后用新数据重写。

10-05 22:43
查看更多