我在我的C程序中有不同的位置,我调用fopen
,fwrite
和fclose
。
当满足某些条件时,我想删除我所处理的文件,而不是对其调用fclose
。但是,当我到达fclose时,重新创建调用fopen
时使用的文件名并不是很简单,因此使用remove
是不实际的。
在调用fclose
之前,我是否可以做一些事情,以便实际上我用fopen
打开并使用fwrite
的文件最终不会出现在磁盘上?
。
f = fopen(filename,"wt");
...
fwrite(f,...)
...
// How can I undo here the effect of fopen and fwrite without knowledge of filename?
这是未经测试的代码,但这应该可以做你想要的:
// 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");
}
如果我总结一下我得到的所有评论,我的问题的答案如下:
不,对于在所有平台上运行的安全代码,一旦调用了fopen
,就需要调用fclose
,然后再调用remove
。
听起来像在c中从文件描述符中检索文件名。也许你可以找到一个解决方案来获得文件名。