警告:使用`tmpnam'是危险的,最好使用`mkstemp' [英] warning: the use of `tmpnam' is dangerous, better use `mkstemp'
问题描述
(注意:这不是不是重复的问题)
(Note: This is not a duplicate question)
我正在使用libc函数 tmpnam
,并收到以下警告:
I'm using the libc function tmpnam
, and getting the following warning:
warning: the use of 'tmpnam' is dangerous, better use 'mkstemp'
我的问题不是如何禁用警告",而是我应该使用什么功能"? mkstemp
没有帮助,因为我没有尝试创建临时文件-我正在创建临时的目录.而AFAIK则没有API函数.
My question isn't "how to disable the warning", but rather "what function should I be using instead"? mkstemp
doesn't help, because I'm not trying to create a temporary file - I'm creating a temporary directory. And AFAIK, there isn't an API function for that.
因此,如果我不应该使用 tmpnam
,那么我应该使用什么 am ?
So if I'm not supposed to use tmpnam
, what am I supposed to use?
推荐答案
您正在寻找 mkdtemp
:
You're looking for mkdtemp
:
mkdtemp - create a unique temporary directory
例如
#include <stdlib.h>
#include <string.h>
...
char templatebuf[80];
char *mkdirectory = mkdtemp(strcpy(templatebuf, "/tmp/mkprogXXXXXX"));
使用 strcpy
来确保传递给 mkdtemp
的参数是可写的(c89),或者
using strcpy
to ensure the parameter passed to mkdtemp
is writable (c89), or
#include <stdlib.h>
...
char templatebuf[] = "/tmp/mkprogXXXXXX";
char *mkdirectory = mkdtemp(templatebuf);
使用c99.
由于该功能是新功能"(虽然在1990年代中期才在Linux上提供,但仅在过去十年内得到了标准化),因此您需要在带有预处理器定义的头文件中打开该功能(可能与一个平台到另一个平台).对于Linux,最简单的方法是定义 _GNU_SOURCE
,例如
Since the feature is "new" (only standardized within the past ten years, though provided in the mid-1990s on Linux), you need to turn the feature on in the header files with a preprocessor definition (which may differ from one platform to another). The simplest for Linux is to define _GNU_SOURCE
, e.g.,
gcc -D_GNU_SOURCE -o foo foo.c
这篇关于警告:使用`tmpnam'是危险的,最好使用`mkstemp'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!