Home > Software design >  In C, how to delete a file that hasn't been closed yet?
In C, how to delete a file that hasn't been closed yet?

Time:01-05

I have separate locations in my C program where I call fopen, fwrite and fclose.

When some conditions are met, I want to delete the file I worked on instead of calling fclose on it. However, by the time I reach fclose, it isn't trivial to recreate the file name I used when calling fopen so using remove isn't practical.

Is there something I can do instead or before calling fclose so that in effect the file I opened with fopen and used fwrite on will not show up on disk in the end?

E.g.

f = fopen(filename,"wt");
...
fwrite(f,...)
...
// How can I undo here the effect of fopen and fwrite without knowledge of filename?

CodePudding user response:

This is untested code, but this should maybe do what you want:

// store both file pointer and file name to be able to delete the file
struct file_info {
    const char *filename;
    FILE *fp;
};


struct file_info file; // uninitialized, remember to initialize all fields
file.filename = "whatever"; // consider ownership of this string!
file.fp = fopen(file.filename, "wt");
if (!file.fp) {
    perror("fopen");
    exit(EXIT_FAILURE); // following code would crash with file.fp=NULL
}
// possibly make the buffer larger with setvbuf to prevent flushing

// do file operations

// abort

// stop any IO on this file descriptor
if (close(fileno(file.fp)) == -1) {
    perror("warning: close fail");
}

// clean up the FILE* structure, the file descriptor should be invalid,
// on condition that you must not open new files between close and fclose!
if (fclose(file.fp) == 0) {
    fputs("warning: fclose success", stderr);
}

// delete after closing the file, otherwise will not work on Windows
if (remove(file.filename) == -1) {
    perror("warning: remove fail");
}

CodePudding user response:

Sounds like Retrieve filename from file descriptor in C. Maybe you can find a solution to get the filename there.

  • Related