fastest way of writing n bytes in a file in c++

2.4k Views Asked by At

I'm not to much familiar with c++ , just wanted to create a text file and write (n) bytes in it , as fast as possible. Using vc6 , any help will be appreciated.

2

There are 2 best solutions below

0
On

Fastest to write bytes... Use std::fwrite. Example copied and slightly edited:

/* fwrite example : write buffer */
#include <cstdio>

int main ()
{
  FILE * pFile;
  char buffer[] = { 'x' , 'y' , 'z' };
  pFile = std::fopen ("myfile.bin", "wb");
  if (!pFile) return 1;
  std::fwrite (buffer , sizeof(char), sizeof(buffer), pFile);
  // code ignores fwrite error, in real app check it!
  std::fclose (pFile);
  // code ignores fclose error, in real app check it!
  return 0;
}

This might not be what you really want to do, but it is the answer to the question... To get possibly better answer, tell what kind of data you actually want to write and with what constraints (in a new question, after experimenting with this)...

0
On

Fput is good for strings, fwrite for anything. You can use ofstream, and manipulate with its buffer for perfomance check this: Does C++ ofstream file writing use a buffer? .