tags:

views:

85

answers:

5
#include<stdio.h>

int main() {

    FILE* fp;
    fp = fopen("temp.txt", "w");
    fprintf(fp, "Hello, World!\n");

    // remove("temp.txt");  this requires the filename as an argument
    // removefile(fp);      <--- is something like this possible?

    return 0;
}

The remove function (defined in stdio.h) takes the file name as a parameter, but not the file pointer itself.

Is there some function in the C standard libraries that does file deletion, and takes file pointer as the arguement?

+1  A: 

No, there isn't (unfortunately).

Bart van Ingen Schenau
+6  A: 

I don't believe there's any way to do this, because a FILE* may not necessarily correspond to a file in the filesystem at all (For example, stdin and stdout).

And in filesystems that support hard links, there can be multiple paths referring to the same underlying file, which one would you want it to remove?

David Gelhar
+1  A: 

No, you can't. And FILE struct doesn't include filename inside it. So best option is to have structure that will both hold pointer to FILE and to char* with name

Andrey
+1  A: 

You closed pointer, then her value was freed, how you imagine delete file by this handle?

Svisstack
while your idea is correct it is not set to NULL in sample.
Andrey
@Audrey: `Closes the file associated with the stream and disassociates it.`
Svisstack
corret, it's not set to null. It's a pointing to freed memory, and potential for a segv/gpf. In fact, you should add a 'fp = 0' line just after the fclose().
Vardhan Varma
@Svisstack: can I do the same before closing the file handle?
Lazer
@Lazer: no, because you can write a wrapper for operating files function, to save filename path while fopen is calling by wrapper, and if you call fclose via wrapper, file was be fclose and deleted by char* previously saved.
Svisstack
+4  A: 

You may want to use the 'FILE * tmpfile(void)' function from stdlib.

from the man:

DESCRIPTION

The tmpfile() function shall create a temporary file and open a corresponding stream. The file shall be automatically deleted when all references to the file are closed. The file is opened as in fopen() for update (w+).

In some implementations, a permanent file may be left behind if the process calling tmpfile() is killed while it is processing a call to tmpfile().

An error message may be written to standard error if the stream cannot be opened.

Vardhan Varma