在C ++中直接访问文件?

时间:2011-04-29 10:51:18

标签: c++ c cross-platform

有没有办法在c ++中没有缓存直接写入磁盘? 目前我正在使用:

int open(fileout, O_CREATE | O_WRONLY | O_DIRECT);  
FILE *fh = fdopen(fileout_dev, "wb");

是否有跨平台库允许这样做?

谢谢阿曼。

1 个答案:

答案 0 :(得分:1)

如果您正在谈论缓冲,那么您可以使用setbufsetvbuf

/* setbuf example */
#include <stdio.h>

int main ()
{
  char buffer[BUFSIZ];
  FILE *pFile1, *pFile2;

  pFile1=fopen ("myfile.txt","w");
  pFile2=fopen ("myfile2.txt","a");

  setbuf ( pFile1 , buffer );
  fputs ("This is sent to a buffered stream",pFile1);
  fflush (pFile1);

  setbuf ( pFile2 , NULL );
  fputs ("This is sent to an unbuffered stream",pFile2);

  fclose (pFile1);
  fclose (pFile2);

  return 0;
}


/* setvbuf example */
#include <stdio.h>

int main ()
{
  FILE *pFile;

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

  // _IONBF disables buffering
  setvbuf (pFile , NULL , _IONBF, 0);

  // File operations here

  fclose (pFile);

  return 0;
}