使用mkstemp()创建的文件被删除时? [英] When a file created with mkstemp() is deleted?

查看:52
本文介绍了使用mkstemp()创建的文件被删除时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序调用mkstemp(),用返回的fd编写一些内容,然后关闭fd.我希望文件一直保留到我自己删除它为止!用rm命令之类的东西.我的问题是:Linux将在close(fd)之后删除此文件吗?

I have a program that calls mkstemp(), writes some stuff with the fd returned and then closes the fd. I want the file to remain until I delete it myself! With something like rm command, or whatever. My question is: will Linux delete this file after close(fd)?

推荐答案

Linux将在close(fd)之后删除此文件吗?

will Linux delete this file after close(fd)?

不是自动的.您需要手动调用文件上的 unlink .如果您不需要按名称访问文件(即通过文件系统),则可以在调用 mkstemp 后立即执行此操作-关闭描述符后,该文件将被删除.

Not automatically. You need to call unlink on the file manually. You can do this immediately after calling mkstemp if you don’t need to access the file by name (i.e. via the file system) — it will then be deleted once the descriptor is closed.

或者,如果您需要按名称将文件传递到代码(或过程)的另一部分,请不要立即调用 unlink .

Alternatively, if you need to pass the file on to another part of the code (or process) by name, don’t call unlink just yet.

以下是工作流程示例:

char filename[] = "tempfile-XXXXXX";
int fd;
if ((fd = mkstemp(filename)) == -1) {
    fprintf(stderr, "Failed with error %s\n", strerror(errno));
    return -1;
}

unlink(filename);

FILE *fh = fdopen(fd, "w");
fprintf(fh, "It worked!\n");
fclose(fh);

fclose 关闭 FILE * 流,同时关闭基础文件描述符,因此我们无需显式调用 close(fd).

fclose closes the FILE* stream, but also the underlying file descriptor, so we don’t need to explicitly call close(fd).

必要的标题:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

这篇关于使用mkstemp()创建的文件被删除时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆