Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1723116
  • 博文数量: 199
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 6186
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-30 11:01
个人简介

Linuxer.

文章存档

2015年(4)

2014年(28)

2013年(167)

分类: LINUX

2013-11-07 15:40:21

每个进程都有一个当前工作目录,此目录是搜索所有相对路径名的起点.

当前工作目录是进程的一个属性.

 

 1) 获取当前工作目录:

#include

 

char *getcwd(char *buf,size_t size);

char *get_current_dir_name(void);

char *getwd(char *buf);

 

getcwd()获取当前工作目录绝对路径并复制到参数buf指向的内存空间,size为buf的空间大小. size要足够大,如果当前工作目录的绝对路径的字符串长度超过size大小, 则返回值为NULL.  如果参数buf为NULL,getcwd()会根据工作目录绝对路径的字符串长度来决定配置的内存大小.  进程可以在使用完此字符串后, 利用free()来释放空间.

 

如果定义了_GNU_SOURCE,则也可以使用get_current_dir_name()来获取当前工作目录;

 

如果定义了_BSD_SOURCE或_XOPEN_SOURCE_EXTENDED,也可以使用getwd获取当前工作目录.

 

2)设置工作目录:

 

#include

int chdir(const char *path);

int fchdir(int fd);

 

3)打开目录:

 

#include

#include

 

DIR *opendir(const char *name);

 

4) 读取目录信息:

 

#include

#include

struct dirent *readdir(DIR *dir);

 

struct dirent{

    long d_ino;      /*inode number*/

    off_t   d_off;   /*offset to this dirent*/

    unsigned short d_reclen;   /*length of this d_name*/

   char d_name[NAME_MAX+1];    /*file name(null-terminated)*/

};

 

5)关闭目录:

 

#include

#include

int closedir(DIR *dir);

 

ONE example:

 

#include

#include

#include

#include

int my_readdir(const char *path)

{

    DIR *dir;

   struct dirent *ptr;

 

   if((dir=opendir(path))==NULL)

         return -1;

   while((ptr=readdir(dir))!=NULL)

          printf("file name: /n",ptr->d_name);

   closedir(dir);

   return 0;

}

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