Advanced Programming in UNIX Environment Episode 24

临时文件

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

#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函数的应用

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...