Chinaunix首页 | 论坛 | 博客
  • 博客访问: 544589
  • 博文数量: 92
  • 博客积分: 2511
  • 博客等级: 少校
  • 技术积分: 932
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-19 10:10
文章分类
文章存档

2011年(6)

2010年(27)

2009年(37)

2008年(22)

我的朋友

分类: LINUX

2010-01-05 22:52:29

   一般的,如果要获得当前进程的当前工作目录(CWD)的话,显然要用到如下函数:
#include
char * getcwd (char *buf, size_t size);
这个函数的使用时显而易见的就是传递一个size长度的缓冲区,然后函数调用会填充这个缓冲区,出错情况下返回NULL,这里不讨论这个函数的一般使用,而是要说一点关于这个函数在Linux下的一个特殊使用方法:
POSIX dictates that the behavior of getcwd( ) is undefined if buf is NULL. Linux’s C
library, in this case, will allocate a buffer of length size bytes, and store the current
working directory there. If size is 0, the C library will allocate a buffer sufficiently
large to store the current working directory. It is then the application’s responsibility
to free the buffer, via free( ), when it’s done with it. Because this behavior is Linux-
specific, applications that value portability or a strict adherence to POSIX should not
rely on this functionality. This feature, however, does make usage very simple!
Here’s an example:

char *cwd;
cwd = getcwd (NULL, 0);
if (!cwd) {
        perror ("getcwd");
        exit (EXIT_FAILURE);
}
printf ("cwd = %s\n", cwd);
free (cwd);

Linux’s C library also provides a get_current_dir_name( ) fu
same behavior as getcwd( ) when passed a NULL buf and a size 
#define _GNU_SOURCE
#include
char * get_current_dir_name (void);
Thus, this snippet behaves the same as the previous one:

char *cwd;
cwd = get_current_dir_name ( );
if (!cwd) {
        perror ("get_current_dir_name");
        exit (EXIT_FAILURE);
}
printf ("cwd = %s\n", cwd);
free (cwd);


阅读(891) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~