目录属性及系统调用(C语言)

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
image

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];/*文件名*/ 

image

目录基本操作

功能

打开。关闭,读,定位

头文件

#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")
    }
}  

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值