在Linux中用C程序创建临时文件

时间:2014-02-03 00:05:58

标签: c linux bash gcc

在Linux中从C程序创建临时文件的最简单方法是什么?

我们可以调用系统函数并使用mktemp

system("TMPFILENAME=$(mktemp tmp.XXXXXXXX)");

或者我们可以使用功能

mkstemp函数或我们可以使用tmpfiletmpnam函数。

1 个答案:

答案 0 :(得分:2)

不要这样做。您应该使用mkstemp功能。这是一个打印您想要的文件名称以及其他信息的示例:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void)
{
    // buffer to hold the temporary file name
    char nameBuff[32];
    // buffer to hold data to be written/read to/from temporary file
    char buffer[24];
    int filedes = -1,count=0;

    // memset the buffers to 0
    memset(nameBuff,0,sizeof(nameBuff));
    memset(buffer,0,sizeof(buffer));

    // Copy the relevant information in the buffers
    strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",21);
    strncpy(buffer,"Hello World",11);

    errno = 0;
    // Create the temporary file, this function will replace the 'X's
    filedes = mkstemp(nameBuff);

    // Call unlink so that whenever the file is closed or the program exits
    // the temporary file is deleted
    unlink(nameBuff);

    if(filedes<1)
    {
        printf("\n Creation of temp file failed with error [%s]\n",strerror(errno));
        return 1;
    }
    else
    {
        printf("\n Temporary file [%s] created\n", nameBuff);
    }
}

有关函数的参考,请查看here