mhk
mhk

Reputation: 345

Can I write to hard disk at 1 Gbps?

I am a bit surprised with the disk speeds that I am getting ..I seem to be able to write a 1GB file under 1 sec..

size_t s = 1*1024*1024;
char* c = new char[s];
FILE* fx = fopen("D:\\test.mine", "wb");
//ensure(fx);
for(int i = 0; i < 1024; ++i)
{
    fwrite(c,1,s,fx);
}
fclose(fx);
delete[] c;

I am a bit hardpressed to understand what could have caused this? I thought fclose ensured that the data is actually written on the hard disk...?

Upvotes: 3

Views: 647

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126907

The standard library functions for writing on files just manage their own internal buffers. When writing on files in a modern operating system, even after the fclose the data actually just goes in the buffers of the operating system, which will delay the write until it thinks it's a good moment.

The usual way to ensure the data is written to disk is to issue an operating-system specific call to force a write to disk; on POSIX it's fsync/sync, on Windows you want FlushFileBuffers.

Upvotes: 9

Marvic
Marvic

Reputation: 167

fclose() also clears the buffer cache of the stream, so the moment you call fclose() the contents of the unread buffer is wiped away.

Upvotes: 0

flolo
flolo

Reputation: 15526

The fclose only flushes the C-library buffers, the system buffers are NOT flushed. Therefor you need a system call, like (f)sync.

Upvotes: 7

Related Questions