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

前端 未结 5 1533
予麋鹿
予麋鹿 2021-01-19 04:56
#include

int main() {

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

    // remove(\"temp.txt\");  this          


        
相关标签:
5条回答
  • 2021-01-19 05:15

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

    0 讨论(0)
  • 2021-01-19 05:22

    No, there isn't (unfortunately).

    0 讨论(0)
  • 2021-01-19 05:23

    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.

    0 讨论(0)
  • 2021-01-19 05:27

    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

    0 讨论(0)
  • 2021-01-19 05:31

    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?

    0 讨论(0)
提交回复
热议问题