Search code examples
cfopenfwrite

What is the fastest way to fill up the free space on a disk in C?


I need a way to fill up the remaining free disk space on a drive with zeros (zero the free apace so that the virtual hard disk don't take space for useless data).

I want speed since the space to fill can be several GB big and I need to use the smallest memory footprint since this will be used in a "vintage" (think 486 with 4MB RAM) environment.

I was thinking to create a file with fopen and fill it with zeros with fwrite and finally delete the file but it seem less than optimal...

I'm not used to write pure C and I'm using a relic compiler (Borland Turbo C 2.01). This is just a fun project to better understand C and at the same time make a small utility for my relic MS-DOS (virtual) environment.

Can you tell me if there is a better way than using fwrite to achieve this?

This is how my code look like so far (untested):

m = malloc(buffSize);
if (!m) {
    return -4;
}
f = fopen(tempFilename, "wb");
if (!f) {
    free(m);
    return -5;
}
i = buffSize;
while (i--) {
    m[i] = 0;
}
written = buffSize;
while (written) {
    written = fwrite(m, buffSize, 1, f);
}
fclose(f);
free(m);

Solution

  • fwrite is probably the fastest way to write things if you restrict yourself to standard C. Be sure to use a large enough all-zero buffer (e.g. 32Kbytes at least). You could use memset to clear that buffer (or the older non-standard bzero), or you could use calloc instead of malloc to allocate it.

    However, your Borland Turbo C is not a very good and C standard compliant compiler.

    Why don't you switch to a more recent compiler and operating system (e.g. some recent Linux and recent GCC)?