2015年1月21日 星期三

[C] Make a temp file under /tmp


/*************************************************************************\
*                  Copyright (C) Michael Kerrisk, 2014.                   *
*                                                                         *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the   *
* Free Software Foundation, either version 3 or (at your option) any      *
* later version. This program is distributed without any warranty.  See   *
* the file COPYING.gpl-v3 for details.                                    *
\*************************************************************************/

#include <stdio.h>

int main()
{
        int fd;
        char template[] = "/tmp/somestringXXXXXXXX";
        fd = mkstemp(template);

        if (fd == -1)
                return 0;
        printf("Generated filename was: %s\n", template);
        unlink(template);
        /* Name disappears immediately, but the file is removed only after close() */
        /* Use file I/O system calls - read(), write(), and so on */
        if (close(fd) == -1)
                return 0;
}


Result :

./mkstemp
Generated filename was: /tmp/somestringXXdmLOVo


Reference:
1. The Linux Programming Interface

0 意見:

張貼留言