foggia2004

mkstemp生成临时文件

使用该函数可以指定目录生成临时文件,函数原型为 int mkstemp(char *template);

应用举例

int main(int argc, char *argv[])
{
    /* char *会产生段错误 */
    /* char *tempname = "mytmpfile_XXXXXX";  */
    
    /* 正确的代码 */
    char tempname[] = "mytmpfile_XXXXXX";
    int fd = mkstemp(tempname);
    if(fd < 0)
    {
        printf("mkstemp failed, exit!\n");
        exit(-1);
    }

    printf("mkstemp succeed, fd : %d\n", fd);
    
    char buf[128];
    memset(buf, 'a', sizeof(buf));
    int result = write(fd, buf, sizeof(buf));
    if(result < 0)
    {
        printf("write buf into file failed, exit!\n");
        exit(-1);
    }

    printf("close fd : %d\n", fd);
    close(fd);
    return 0;
}

执行截图

在当前目录下多出了一个名为"mytmpfile_RzTSGo"的文件,并且该文件被写入了之前预制好的数据.

注意:该函数要求文件名最后6位必须是"XXXXXX", template must not be a string constant, but should be declared as a character array.如果你不小心将tmeplate声明为一个指针,那么你将会得到一个Segmentation fault (core dumped)错误.

 

posted on 2016-12-29 11:00  foggia2004  阅读(253)  评论(0)    收藏  举报

导航