Search code examples
c++winapidiskspace

GetDiskFreeSpaceEx, free space not changing despite creating files


I am trying to write a program to fill a hard drive with files. It's to test the drive's reliability. I write a file, read it to check its contents and move on until the drive is full.

But the function I use to get the drive's free space returns the same value when you call it in a loop. I looked everywhere, but could not find an answer to this question.

I wrote a simple program to show the phenomenon.

int main()
{
    for (int i = 0; i < 3; ++i)
    {
        write128MBFile("F:\\test\\fill\\" + to_string(i));
        cout << getFreeSpace("F:\\test\\fill") << endl;
    }
}

Returns

1 //Meaning that GetDiskFreeSpaceEx was successful
229311180800 //The amount of free bytes left
1
229311180800
1
229311180800

I confirmed that the files have been written. The disk's free space is even updated correctly in the drive's property menu.

Here is getFreeSpace's code:

static unsigned __int64 getFreeSpace(const char* dir)
{
    ULARGE_INTEGER freeBytesUser;
    ULARGE_INTEGER bytes;
    ULARGE_INTEGER freeBytesTotal;
    int i = GetDiskFreeSpaceEx(dir,&freeBytesUser,&bytes,&freeBytesTotal);
    cout << i << endl;
    return freeBytesUser.QuadPart;
}

And here is write128MBFile's code:

void write128MBFile(string fileName)
{
    int fileSize = 1024*1024*128;
    int parts = 8;
    int partSize = fileSize / parts;//Buffer of about 16MB
    char c = 33;
    ofstream outfile;
    outfile.open(fileName, ios::binary | ios::trunc);
    for (int i = 0; i < parts; i++)
    {
        char *partToWrite = new char[partSize + 1];
        partToWrite[partSize] = '\0';
        for (int j = 0; j < partSize; j++)
        {
            partToWrite[j] = c;
        }
        outfile << partToWrite;
        outfile.flush();
        delete partToWrite;
    }
    outfile.close();
}

Can't forget about the includes:

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
using namespace std;

Am I not using the function correctly? I have absolutely no idea what could be causing this. I have something similar written in c#, it uses the DriveInfo class and this problem is not present.


Solution

  • Sorry guys, Hans Passant was right, it was a very simple mistake. The code was overwriting files with ones that were the same size, so the free space never changed.

    For the record, both freeBytesUser and freeBytesTotal give me the same results. This was done on windows 7 64 bit.