ls的编写

ls就是对目录的操作, 直接上代码

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#include<stdlib.h>

#define BUFFSIZE   512

ino_t GetInode(char*);
void PrintDirPath(ino_t);
void GetDirNameByInode(ino_t,char*,int);

int main(int ac, char* av[]){

    PrintDirPath(GetInode("."));
    putchar('\n');
    return 0;
}

void PrintDirPath(ino_t nCurrentInode){
    ino_t nFatherInode;
    char cDirName[BUFFSIZE];

    if(GetInode("..") != nCurrentInode){
        //获取当前目录的名字
        GetDirNameByInode(nCurrentInode,cDirName,BUFFSIZE);

        //递归调用,找父目录,直到根目录
        chdir("..");
        nFatherInode = GetInode(".");
        PrintDirPath(nFatherInode);

        //打印当前目录名字
        printf("/%s",cDirName);
    }

}

void GetDirNameByInode(ino_t nInodeToFind, char* pNameBuf,int nBufLen){
    DIR *pDir;
    struct dirent * pDirent;
    //打开当前的目录文件
    pDir = opendir(".");
    if(!pDir){
        perror(".");
        exit(1);
    }

    //逐条读取目录文件,和目标inode做比对,如果找到,就读取其目录名
    while(pDirent = readdir(pDir)){
        if(pDirent->d_ino == nInodeToFind){
            strncpy(pNameBuf,pDirent->d_name,nBufLen);
            pNameBuf[nBufLen-1] ='\0';
            closedir(pDir);
            return;
        }
    }

    fprintf(stderr,"error looking for inum %d\n",nInodeToFind);
    closedir(pDir);
    exit(1);
}

//通过目录名获取inode节点的node号
ino_t GetInode(char* pDirName){
     struct stat info;
     if(-1 == stat(pDirName,&info)){
         fprintf(stderr,"Cannot stat");
         perror(pDirName);
         exit(1);
     }
     return info.st_ino;
}

 

转载于:https://www.cnblogs.com/XiangWei1/p/6740522.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值