mkdir()/tmdir()系统调用
功能
创建/删除一个空目录
头文件
#include<sys/stat.h>
#include<sys/types.h>
函数原型
int mkdir(const char *pathname,mode_t mode);
int rmdir(const char *pathname);
返回值
成功时返回0
失败时放回-1
chdir()/fchdir()系统调用
功能
更改工作目录
头文件
#include<unistd.h>
函数原型
int chdir(const char* path);
int fchdir(int fd);
返回值
成功时返回0
失败时返回-1
说明
当前工作目录时进程的属性,所以该函数只影响调用chdir的进程本身
getcwd()系统调用
功能
获取当前工作目录的绝对路径
头文件
#include<unistd.h>
函数原型
cahr *getcwd(char *buf,size_t size);
返回值
成功时返回buf
出错则为NULL
注意
1.在调用此函数时,buf所指的内存空间要足够大。若工作目录绝对路径的字符串长度超过size大小,则返回NULL,errno的值则为ERANGE
2.倘若参数buf为NULL,getcwd()会依参数size的大小自动配置内存(使用malloc()),如果参数size也为0,则getcwd()会依工作目录绝对路径的字符串长度来决定所配置的内存大小,进程可以在使用完字符串后利用free()来释放此空间
实例
printf("%s",getcwd(NULL,NULL));
char *ptr=(char *)malloc(size*sizeof(char));
getcwd(ptr,size);
perintf(("work dir is:%s\n",ptr);
free(ptr);
读取目录信息
数据结构
DIR
目录流对象
头文件
#include<dirent.h>
定义形式
typedf struct_dirstream DIR
struct dirent
目录项
头文件
#include<dirent.h>
定义
ino_t ino;/*inode号/
char d_name[NAME_MAX+1];/*文件名*/
目录基本操作
功能
打开。关闭,读,定位
头文件
#include<sys/types.h>
#include<dirent.h>
函数原型
DIR*opendir(const char*name);
int closedir(DIR *dir);
struct dirent *readdir(DIR *dir);
off_t telldir(DIR *dir);//获取目录流读取位置
void seekdir(DIR*dir,off_t offset);
目录扫描程序
DIR *dir;
struct dirent*dirp;
struct stat statbuf;
for(int i=1;i<argc;i++)
{
if(lstat(argv[i],&statbuf)<0)
{
perror("lsata:");
}
if(S_ISDIR(statbuf.st_mode))
{
dir =opendir(argv[i]);
if(dir)
{
while((dirp=readdir(dir))!=NULL){
if(dirp->d_name[0]='.')
continue;
printf("inode=%ld\n",dirp->d_ino);
printf("file name :%s\n",dirp->d_name);
}
}else
perror("opendir error");
closedir(dir);
}else
{
printf("is not directory\n")
}
}