当我使用lcc编译器并调用tmpnam(buf)时,程序就崩溃了。
Reason: L_tmpnam indicates that buf must be 14 bytes long, while the string returned
is "D:\Documents and settings\Paul\Temporary\TmP9.tmp" which is much longer than 14. 我做错了什么,如何解释这种行为。
发布于 2013-04-07 17:33:01
来自man tmpnam的逐字记录
从不使用此函数。改用mkstemp(3)或tmpfile(3)。
不管怎样,正如你所要求的:
tmpnam()生成的名称由文件名maximum L_tmpnam lenght 加上名称P_tmpdir的目录组成。
因此,传递给tmpnam()的缓冲区最好声明(如果为C99):
char pathname[strlen(P_tmpdir) + 1 + L_tmpnam + 1] = ""; /* +1 for dir delimiting `/` and +1 for zero-termination */如果不是C99,你可以这样做:
size_t sizeTmpName = strlen(P_tmpdir) + 1 + L_tmpnam + 1;
char * pathname = calloc(sizeTmpName, sizeof (*pathname));
if (NULL == pathname)
perror("calloc() for 'pathname'");然后像这样调用tmpnam():
if (NULL == tmpnam(pathname))
fprintf(stderr, "tmpnam(): a unique name cannot be generated.\n");
else
printf("unique name: %s\n", pathname);
... /* do soemthing */
/* if on non C99 and calloc(() was called: */
free(pathname);https://stackoverflow.com/questions/15860684
复制相似问题