Advanced Programming in UNIX Environment Episode 24

前端之家收集整理的这篇文章主要介绍了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函数的应用

原文链接:https://www.f2er.com/bash/388842.html

猜你在找的Bash相关文章