int mkstemp(char *template)
测试代码:
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <string.h>
#define DEBUG_INFO(format, ...) printf("%s - %d - %s :: "format"\n",__FILE__,__LINE__,__func__ ,##__VA_ARGS__)
int main(void){
int fd;
char temp_file[]="tmp_XXXXXX";
DEBUG_INFO("创建之前:temp_file = %s",temp_file);
if((fd=mkstemp(temp_file))==-1){
printf("Creat temp file faile./n");
exit(1);
}
DEBUG_INFO("创建之后:temp_file = %s,fd = %d",temp_file,fd);
/*Then you can read or write the temp file.*/
//ADD YOUR CODE;
//close(fd);
write(fd,"hello world",sizeof("hello world"));
lseek(fd,SEEK_SET,0);
int res = access(temp_file,F_OK);
if(res != 0){
perror("access 1:");
}else{
DEBUG_INFO("access %s ok",temp_file);
}
unlink(temp_file);
res = access(temp_file,F_OK);
if(res != 0){
perror("access:");
DEBUG_INFO("access %s fail",temp_file);
}
char buf[100];
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
DEBUG_INFO("buf = %s",buf);
close(fd);
return 0;
}
执行结果:
/big/work/ipc/mkstemp.c - 12 - main :: 创建之前:temp_file = tmp_XXXXXX
/big/work/ipc/mkstemp.c - 17 - main :: 创建之后:temp_file = tmp_3uabCW,fd = 3
/big/work/ipc/mkstemp.c - 28 - main :: access tmp_3uabCW ok
access:: No such file or directory
/big/work/ipc/mkstemp.c - 34 - main :: access tmp_3uabCW fail
/big/work/ipc/mkstemp.c - 40 - main :: buf = hello world
实验解析
小结