推荐使用 tmpfile mkstemp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int
main(void)
{
FILE *pfile,*pfile2;
int fileSize, readSize;
char * fileBuff = NULL;
char buff[128] = { 0 };
<strong>/****************(1) tmpfile() *****************/</strong>
pfile2= tmpfile();
if(pfile2 == NULL)
{
fputs("creat temp file error",stderr);
exit(1);
}
if( EOF == fputs("tmpfile function create me !",pfile2))
{
fputs("write err.\n",stderr);
exit(1);
}
rewind(pfile2); // positions the stream stream at the beginning of the file
fgets(buff,sizeof(buff),pfile2);
puts(buff);
<strong>/********************(2) tmpnam() + unlink() *****************/</strong>
memset(buff,0,sizeof(buff));
puts(tmpnam(buff));
/*************read or write file***************/
pfile = fopen(buff, "a+");
unlink(buff);
if(pfile == NULL )
{
fputs("open error", stderr);
exit(1);
}
if (sizeof("11111111") != fwrite("11111111", sizeof(char), sizeof("11111111") / sizeof(char), pfile))
{
fputs("write error", stderr);
exit(1);
}
//get the file size
fseek(pfile, 0, SEEK_END);
fileSize = ftell(pfile);
rewind(pfile);
printf("filesize:%d\n", fileSize);
fileBuff = (char *) malloc(sizeof(char) * fileSize);
if (fileSize != (readSize = fread(fileBuff, sizeof(char), fileSize, pfile)))
{
fputs("Read error", stderr);
exit(3);
}
else
{
printf("readContent: %s \nreadsize:%d\n",fileBuff,readSize);
}
fclose(pfile);
free(fileBuff);
<strong>/********************(3) fopen() and unlink() **************/</strong>
pfile=NULL;
pfile=fopen("/tmp/tempA.txt","w+");
if(pfile == NULL )
{
fputs("create file failed.",stderr);
exit(1);
}
fputs("fopen create me",pfile);
rewind(pfile);
if( fgets(buff,sizeof(buff),pfile) == NULL )
{
fputs("read file error.\n",stderr);
exit(1);
}
fputs(buff,stdout);
fclose(pfile);
unlink("/tmp/tempA.txt");
puts("\nDONE.......\n");
return EXIT_SUCCESS;
}
int mkstemp(char *template);
mkstemp函数在系统中以唯一的文件名创建一个文件并打开,而且只有当前用户才能访问这个临时文件,并进行读、写操作。
建立唯一临时文件名, template须以数组形式声明而非指针形式.
int main(void)
{
int fd;
char temp_file[]="tmp_XXXXXX";
/*Creat a temp file.*/
if((fd=mkstemp(temp_file))==-1)
{
printf("Creat temp file faile./n");
exit(1);
}
/*Unlink the temp file.*/
unlink(temp_file);
close(fd);
}