Hassaan Salik
Hassaan Salik

Reputation: 413

Effective way to write text file c++

I am trying to write large text files with minimum consumption of time. First of all i have to initialize a file with empty space. My approach is to make a char array of say 250bytes and then copying it into file. I think this isn't much effective way. Any better idea?

char buff[250];
ofstream ofile;
ofile.open("abc.txt");
for(long int i=0;i<20970;i++)
{
  ofile<<buffer;
  ofile<<endl;
 }

Upvotes: 1

Views: 351

Answers (2)

Jasper
Jasper

Reputation: 6556

You can seek to the end of the file and write a single character:

#include <fstream>

using namespace std;

int main(int argc,char** argv) {
    ofstream o("file") ;
    o.seekp(100 * 1024 * 1024);
    o << '\0';

    return 0;
}

This is only effective if you know in advance the size of the resulting file.

Upvotes: 1

Domi
Domi

Reputation: 24528

In Windows, you can create a file of given size, using SetEndOfFile. In Linux it is ftruncate.

Also make sure to optimize your buffer size when writing. The optimal buffer size depends on system internals, such as page size. But in most cases (if it is not an embedded system), 4-128kb is a good size.

Upvotes: 1

Related Questions