如何创建在C临时目录? [英] How to create a temporary directory in C?
问题描述
我想创建一个临时目录,在它执行某些操作,然后删除整个事情的结束。我用C语言在UNIX系统上,所以我想有一些符合这个环境。
I am trying to create a temporary directory to perform some operations in it and then delete the whole thing at the end. I use C language in a UNIX system, so I would like to have some compliance with this environment.
什么是编程最好的方法?
What is the best way to program this ?
修改
我真的需要一个目录,不仅是一个文件。这种小程序的目的是尝试,如果我能SVN项目的结账执行。因此,它应该能够创建文件和目录的全部层次。
EDIT
I really need a directory, not only a file. The small program is intended to try out if I can perform an svn checkout
of a project. So, it should be able to create a full hierarchy of files and directories.
推荐答案
我建议从C API常用功能一起使用 mkdtemp()
函数(的glibc
)。这是一个完整的答案:
I suggest to use the mkdtemp()
function together with usual functions from the C API (glibc
). Here is a full answer:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int
main ()
{
/* Create the temporary directory */
char template[] = "/tmp/tmpdir.XXXXXX";
char *tmp_dirname = mkdtemp (template);
if(tmp_dirname == NULL)
{
perror ("tempdir: error: Could not create tmp directory");
exit (EXIT_FAILURE);
}
/* Change directory */
if (chdir (tmp_dirname) == -1)
{
perror ("tempdir: error: ");
exit (EXIT_FAILURE);
}
/******************************/
/***** Do your stuff here *****/
/******************************/
/* Delete the temporary directory */
char rm_command[26];
strncpy (rm_command, "rm -rf ", 7 + 1);
strncat (rm_command, tmp_dirname, strlen (tmp_dirname) + 1);
if (system (rm_command) == -1)
{
perror ("tempdir: error: ");
exit (EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
这篇关于如何创建在C临时目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!