• 产生唯一的临时文件mkstemp()


    INUX下建立临时的方法(函数)有很多, mktemp, tmpfile等等. 今天只推荐最安全最好用的一种: mkstemp.

    mkstemp (建立唯一临时文件)
    头文件: #include <stdlib.h>

    声明:   int mkstemp(char *template)
    返回值: 成功则返回0, 失败则返回-1
    .
    说明:  建立唯一临时文件名, template须以数组形式声明而非指针形式. 
            template格式为: template.XXXXXX. 最后6位必须为XXXXXX, 前缀随意.

    //1.mkstemp函数在系统中以唯一的文件名创建一个文件并打开,而且只有当前用户才能访问这个临时文件,
    //2.mkstemp函数只有一个参数,这个参数是个以“XXXXXX”结尾的非空字符串。mkstemp函数会用随机产生的字符串替换“XXXXXX”,保证 了文件名的唯一性
    //3.由于mkstemp函数创建的临时文件不能自动删除,所以执行完 mkstemp函数后要调用unlink函数,unlink函数删除文件的目录入口

    char temp_template[] = "/tmp/htp.XXXXXX";

    tfd = mkstemp(temp_template);
    if(!(tfp = fdopen(tfd,"w"))) {
    fprintf(stderr,"Could not open temp file. ");
    exit(1);
    }

    #include<stdio.h>
    #include<stdlib.h>
    int main(void)
    {
    int fd;
    char temp_file[]="tmp_XXXXXX";
    /*Creat a temp file.*/
    if((fd=mkstemp(temp_file))==-1)
    {
    printf("Creat temp file faile./n");
    exit(1);
    }
    /*Unlink the temp file.*/
    unlink(temp_file);
    /*Then you can read or write the temp file.*/
    //ADD YOUR CODE;
    /*Close temp file, when exit this program, the temp file will be removed.*/
    close(fd);
    }
  • 相关阅读:
    利用ResultFilter实现asp.net mvc3 页面静态化
    c#的DateTime.Now函数详解
    C#中使用DES和AES加密解密
    C#实现DES加密解密,AES加密解密
    MyEclipse的破解代码,适用各个版本
    C# DataGridView分页显示
    C# 对话框使用大全
    C# 通过串口发送短信
    C# axWindowsMediaPlayer制作播放器
    C#关于log4net(Log For Net)
  • 原文地址:https://www.cnblogs.com/zhouhbing/p/4201126.html
Copyright © 2020-2023  润新知