我继承了以下代码:

void *buf1 = calloc(1,total_buf_size);
//build buf1 up with memcpy
int index;
void *buf2 = buf1;

for (index = 0; index < log->numentries; index++)
{
  logentry_t *entry = (logentry_t*)&log->entries[index];

  memcpy(buf2,entry->entryname,sizeof(entry->entryname));
  buf2 = buf2 + (int)sizeof(entry->entryname);
  memcpy(buf2,&entry->entrysize,sizeof(entry->entrysize));
  buf2 = buf2 + (int)sizeof(entry->entrysize);
  memcpy(buf2,&entry->updatesize,sizeof(entry->updatesize));
  buf2 = buf2 + (int)sizeof(entry->updatesize);
  memcpy(buf2,&entry->numupdates,sizeof(entry->numupdates));
  buf2  = buf2 + (int)sizeof(entry->numupdates);

  int j;
  for (j = 0; j < entry->numupdates; j++)
  {
    memcpy(buf2,&entry->offsets[j],sizeof(entry->offsets[j]));
    buf2 = buf2 + (int)sizeof(entry->offsets[j]);
  }

  int k;
  for (k = 0; k < entry->numupdates; k++)
  {
    memcpy(buf2,&entry->sizes[k],sizeof(entry->sizes[k]));
    buf2 = buf2 + (int)sizeof(entry->sizes[k]);
  }


  memcpy(buf2,entry->data,entry->updatesize);
}

我有一个正在迭代的事务日志,需要将每个日志条目的数据写入文件中的一行。目前它正在使用memcpy为所有条目构建一个缓冲区,并将它们一次全部写入文件。有没有更好的方法将内存复制并扩展到buf2中?

最佳答案

我不确定你到底在寻找什么样的效率,但这里有一个将每个日志条目记录写到文件中,然后为每次迭代重置缓冲区buf2的例子。因此,您可以将buf1大小(由total_buf_size定义)减少到只适合一个日志条目记录的大小:

void *buf1 = calloc(1,total_buf_size);
//With this method total_buf_size can be reduced to fit just one log entry record

//build buf1 up with memcpy
int index;
void *buf2 = buf1;

FILE * pFile;
pFile = fopen ("myfile.txt","w");

for (index = 0; index < log->numentries; index++)
{
  logentry_t *entry = (logentry_t*)&log->entries[index];

  memcpy(buf2,entry->entryname,sizeof(entry->entryname));
  buf2 = buf2 + (int)sizeof(entry->entryname);
  memcpy(buf2,&entry->entrysize,sizeof(entry->entrysize));
  buf2 = buf2 + (int)sizeof(entry->entrysize);
  memcpy(buf2,&entry->updatesize,sizeof(entry->updatesize));
  buf2 = buf2 + (int)sizeof(entry->updatesize);
  memcpy(buf2,&entry->numupdates,sizeof(entry->numupdates));
  buf2  = buf2 + (int)sizeof(entry->numupdates);

  int j;
  for (j = 0; j < entry->numupdates; j++)
  {
    memcpy(buf2,&entry->offsets[j],sizeof(entry->offsets[j]));
    buf2 = buf2 + (int)sizeof(entry->offsets[j]);
  }

  int k;
  for (k = 0; k < entry->numupdates; k++)
  {
    memcpy(buf2,&entry->sizes[k],sizeof(entry->sizes[k]));
    buf2 = buf2 + (int)sizeof(entry->sizes[k]);
  }


  memcpy(buf2,entry->data,entry->updatesize);

  fwrite(buf2, sizeof(logentry_t), sizeof(buf2), pFile);

  memset(&buf2, 0, sizeof(buf2)); //clear it out
  buf2 = buf1; //reset the pointer
}

fclose(pFile);
free(buf2);

09-04 14:16