Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a file pointed to by a FILE* in C?

Tags:

c

file-io

#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?

like image 395
Lazer Avatar asked Sep 07 '10 10:09

Lazer


People also ask

How do you delete a file in C?

Delete File in C Programming To delete a file using C language, use remove() function of stdio. h. remove() function takes file name (or path if not located in the same location) as argument and deletes the file. remove() returns 0 if the file is deleted successfully, else it returns a non-zero value.

How do I delete a file with a specific name?

From Explorer To delete matching files: enter *_bad. jpg in the search box, select the results and press Delete or Del.

How do I delete a file to delete?

Click Delete in the File Explorer Ribbon at the top of the window, or click the arrow underneath the Delete option and select Permanently delete. Clicking Delete sends the file to the Recycle Bin, while selecting the Permanently delete option deletes the file for good.


1 Answers

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?

like image 191
David Gelhar Avatar answered Oct 12 '22 04:10

David Gelhar