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;
}

 

posted @ 2017-04-20 19:52  xwqaz  阅读(186)  评论(0编辑  收藏  举报