Arman
Arman

Reputation: 4636

Direct file access in C++?

Are there way to write directly to disk without cache in c++? Currently I am using:

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

Are there cross platform libraries allowing to do that?

Thanks Arman.

Upvotes: 1

Views: 941

Answers (1)

RC.
RC.

Reputation: 28257

If you're talking about buffering, then you can use setbuf or setvbuf

/* 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;
}

Upvotes: 1

Related Questions