Chinaunix首页 | 论坛 | 博客
  • 博客访问: 969068
  • 博文数量: 200
  • 博客积分: 5011
  • 博客等级: 大校
  • 技术积分: 2479
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-27 15:07
文章分类

全部博文(200)

文章存档

2009年(12)

2008年(190)

我的朋友

分类:

2008-11-06 19:16:14

5.13 temporary files

ISO c里面有两个function是用来产生临时文件的

#include

 

char *tmpnam(char *ptr);

 

Returns: pointer to unique pathname

FILE *tmpfile(void);

 

Returns: file pointer if OK, NULL on error

tmpnam用来产生一个临时文件名,如果ptr=NULL,那么产生的名字放在一个static存储区里,并且返回值即是这个缓冲区的指针。所以不能删除,而且第2次调用该函数的时候,该缓冲区就被新的名字覆盖了,因此每次调用的结果都应该复制到别的缓冲区里面去。

Tmpfile函数产生一个临时文件,并且打开他,而且该文件是可读写的,并且当你关闭干文件或者程序退出的时(会自动关闭文件),该文件会被自动remove掉。怎么实现的呢?还记得unlink函数么? 当你unlink一个文件后,如果该文件的link数便成了0 那么该文件的inode以及文件内容理应被remove,但如果此时该文件已经被某个进程打开了,那么其内容还不会被删除,等该进程将其关闭,或者进程退出时,该文件内容就被删除了。所以这个函数就是打开了一个临时文件,然后紧接着就将其unlink了。

如下是SINGLE unix specification定义的用来处理临时文件的XSI extension包含的函数:

#include

 

char *tempnam(const char *directory, const char

 *prefix);

 

Returns: pointer to unique pathname

 

#include

 

int mkstemp(char *template);

 

Returns: file descriptor if OK, 1 on error

Tempnam函数可以接受你提供的目录,和文件名前缀参数,不过,他并不严格使用你指定的目录,它有自己的策略:

1If the environment variable TMPDIR is defined, it is used as the directory. (We describe environment variables in .)

2If directory is not NULL, it is used as the directory.

3The string P_tmpdir in is used as the directory.

4A local directory, usually /tmp, is used as the directory.

If the prefix argument is not NULL, it should be a string of up to five bytes to be used as the first characters of the filename.

这个函数返回的文件名是malloc的,因此你可以自己删除。

Mkstemp函数根据你提供的文件名字模板创建临时文件,并且返回文件的descriptor。但是在关闭文件时不会自动删除文件。

 

Tempnamtmpnam有个弊端:他们会创造没有冲突的临时文件名,但是当你获得了这个名在,在创立该文件之前,有可能别的进程就创建了一个使用了这个名字的文件,这样就有问题了,所以,建议在有可能别的进程在相应目录下也创建临时文件的时候不要使用这个方法。当然我们可以通过限定目录和前缀来解决这个问题。

 

阅读(523) | 评论(0) | 转发(0) |
0

上一篇:filezillar的编译安装

下一篇:_T("string") macro

给主人留下些什么吧!~~