Linux C创建临时文件mktemp, mkstemp

mktemp 创建临时文件名

创建一个独特的文件名,每次调用得到的文件名都不一样。

注意:该函数只产生文件名,并不创建文件。

#include <stdlib.h>

char *mktemp(char *template);
  • 参数
    template 必须是一个字符数组,末尾6个字符必须是"XXXXXX",比如可以是"test-XXXXXX"(不含目录),或者"/tmp/test.XXXXXX"(含目录),而且不能是字符串常量。因为函数会改变template最后6个字符,返回最终文件名

  • 返回值
    返回的是得到的最终唯一文件名 。是否包含目录目,取决于输入参数template是否包含了目录。

mktemp存在严重的安全风险,不建议使用,建议使用mkstemp。因为一些4.3BSD实现用当前进程ID和单个字母来替换 XXXXXX
man mktemp(3)

BUGS
Never use mktemp(). Some implementations follow 4.3BSD and replace XXXXXX by
the current process ID and a single letter, so that at most 26 different
names can be returned. Since on the one hand the names are easy to guess,
and on the other hand there is a race between testing whether the name exists
and opening the file, every use of mktemp() is a security risk. The race is
avoided by mkstemp(3).

示例:

char *tt = "test-XXXXXX";
char template[256];
char *s;

strcpy(template, tt);
s = mktemp(template);
printf("template = %s, s = %s\n", template, s);

运行结果(每次产生的文件名都不一样):

template = test-9ZTDNE, s = test-9ZTDNE

mkstemp 创建临时文件

每次调用,会创建一个临时文件,并且临时文件名唯一。

#include <stdlib.h>

int mkstemp(char *template);
  • 参数
    template 同mktemp,必须是字符数组,且以"XXXXXX"结尾,不能是字符串常量。

  • 返回值
    指向临时文件的文件描述符

示例:

char name[256] = "test.XXXXXX";
int fd;
if ((fd = mkstemp(name)) < 0) {
    perror("mktemp error");
    return -1;
}

strcpy(name, name);
unlink(name); /* 进程结束后自动删除文件 */

printf("%s\n", name);
char buf[256];
strcpy(buf, "hello, world");
if (write(fd, buf, strlen(buf)) < 0) {
    perror("write");
    return -1;
}

close(fd);

运行结果(会在当前目录下产生临时文件,并且打印):

test.5C0SaB
posted @ 2021-07-14 11:13  明明1109  阅读(1908)  评论(0编辑  收藏  举报