Advanced Programming in UNIX Environment Episode 24

本文介绍了在C语言中如何使用tmpnam、tmpfile、mkdtemp和mkstemp等函数来创建临时文件,并通过示例代码展示了这些函数的具体应用。特别关注了如何避免临时文件名被其他进程利用的安全隐患。

临时文件

提供了两个函数以帮助创建临时文件。

#include <stdio.h>

char *tmpnam(char *ptr);
FILE *tmpfile(void);

嘴多调用次数是TMP_MAX。TMP_MAX定义在 <stdio.h>中。

#include "apue.h"

int main(void)
{
    char name[L_tmpnam],line[MAXLINE];
    FILE *fp;

    printf("%s\n",name);

    tmpnam(name);
    printf("%s\n",name);

    if((fp=tmpfile())==NULL)
        err_sys("tmpfile error");
    fputs("one line of output\n",fp);
    rewind(fp);
    if(gets(line, sizeof(line),fp)==NULL)
        err_sys("fgets error");
    fputs(line,stdout);

    return 0;
}

tmpnam和tmpfile函数实例

Single UNIX Specification为处理临时定义了另外两个函数:mkdtemp和mkstemp,他们是XSI的扩展部分。

#include <stdlib.h>

char *mkdtemp(char *template);
int mkstemp(char *template);

使用tmpnam和tempnam至少有一个缺点:再返回唯一的路径名和用该名字创建文件之间存在一个时间窗口,在这个时间窗口中,另一个进程可以用相同名字创建文件。

#include "apue.h"

void make_temp(char *template);

int main(void)
{
    char good_template[]="/tmp/dirXXXXXX";
    char *bad_template[]="/tmp/dirXXXXXX";

    printf("trying to create first temp file...\n");
    make_temp(good_template);
    printf("trying to create second temp file...\n");
    make_temp(bad_template);

    return 0;
}

void make_temp(char *template)
{
    int fd;
    struct stat sbuf;

    if((fd=mkstemp(template))<0)
        err_sys("can't create temp file");
    printf("temp name=%s\n",template);
    close(fd);
    if(stat(template,&sbuf)<0)
    {
        if(errno==ENOENT)
            printf("file doesn't exist\n");
        else
            err_sys("stat failed");
    }
    else
    {
        printf("file exists\n");
        unlink(template);
    }
}

mkstemp函数的应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值