Search code examples
file-iofwritefile-rename

Is it possible to rename a file when it's still in OS / Disk driver's cache?


For instance, I write a large buffer to a temp file then immediately rename the file. What will happen?

const char* tmp_file = "test.bin.tmp";
const char* real_file = "test.bin";

FILE* fp = fopen(tmp_file, "w+b");
if(fp)
{
    fwrite(large_buffer, sizeof(large_buffer), 1, fp);
    fclose(fp);

    // Here, assume that the data is still in the OS's / Disk driver's cache
    rename(tmp_file, real_file);
}

Solution

  • The OS will flush out the cache and then perform the rename operation normally.