【问题标题】:Creating temporary file from C program in Linux mint在 Linux mint 中从 C 程序创建临时文件
【发布时间】:2014-02-03 00:05:58
【问题描述】:

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

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

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

或者我们可以使用函数

mkstemp 函数或者我们可以使用tmpfile of tmpnam 函数。

【问题讨论】:

  • 请不要。请改用tmpnam()tmpfile()
  • 也许你实际上应该用 C 来做? linux.die.net/man/3/mktemp
  • 每个系统调用都会调用一个新的 shell 实例。您必须将所有命令放在一个 shell 调用中。
  • @ooga 非常感谢。它确实有效。

标签: c linux bash gcc


【解决方案1】:

不要这样做。您应该使用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

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 2021-01-27
    • 1970-01-01
    • 2013-05-02
    • 2017-02-27
    • 2010-12-19
    • 2014-07-24
    • 1970-01-01
    • 2010-11-04
    相关资源
    最近更新 更多