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

原文链接: https://www.cnblogs.com/fortunely/p/15009966.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    Linux C创建临时文件mktemp, mkstemp

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/402953

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:17
下一篇 2023年4月21日 上午11:17

相关推荐