Implementing the LS () function to traverse the directory under Linux

Source: Internet
Author: User

Requirements: Traverse the directory under Linux and output the file names in the directory.

The related functions that traverse the directory under Linux are:

#include <dirent.h>

dir* opendir (const char* Dir_path);

struct dirent* readdir (dir* dirp);

int Closedir (dir* dirp);

int Lstat (const chat* filename,struct stat* ST);

Several structures are involved here: dir,struct dirent,struct stat:

The dir struct is an internal structure, similar to file, that holds information about the directory currently being read:

truct __dirstream {     void     *__fd;      Char     *__data;      int         __entry_data;      Char     *__ptr;      int        __entry_ptr;     size_t  __allocation;     size_t  __size;     __libc_lock_define (, __lock)};        struct __dirstream DIR;

struct dirent, pointing to directory contents under folder:

structdirent{LongD_ino;/*inode Number Index node*/off_t D_off;/*offset to this dirent in the directory file*/unsigned ShortD_reclen;/*length of this d_name filename long*/unsignedCharD_type;/*The type of d_name file type*/CharD_name [name_max+1];/*File name (null-terminated) file name, maximum 256 characters*/}

The struct stat structure holds the file information, which is returned by the stat (), Fstat (), Lstat ( ) function, and the difference between the three functions is that the stat () incoming file path gets Stat,lstat () when the symbol chain file is passed in, Get the information of the symbolic chain file instead of the file that the symbolic chain points to, Fstat () passes in the file descriptor instead of the file path.

structStat {dev_t St_dev; /*ID of device containing file*/ino_t St_ino; /*inode Number*/mode_t St_mode; /*Protection*/nlink_t St_nlink; /*Number of hard links*/uid_t St_uid; /*User ID of owner*/gid_t St_gid; /*group ID of owner*/dev_t St_rdev; /*Device ID (if special file)*/off_t st_size; /*Total size, in bytes*/blksize_t st_blksize;/*blocksize for file system I/O*/blkcnt_t st_blocks; /*Number of 512B blocks allocated*/time_t st_atime; /*Time of last access*/time_t st_mtime; /*Time of last modification*/time_t st_ctime; /*Time of last status change*/};

The following is the full implementation of the LS () function, with Opendir () to get the dir* pointer, the Readdir () function obtains a pointer to the struct dirent structure, and then obtains the information of each file through the struct Stat. Output the directory file name in alphabetical order before outputting the normal file.

intLS (std::stringPATH,STD::string&ret) {DIR* Dirp =Opendir (Path.c_str ()); if(!dirp) {        return-1; }    structStat St; structDirent *dir; Std::vector&LT;STD::string>file_name; Std::vector&LT;STD::string>Dir_name;  while(dir = Readdir (DIRP))! =NULL) {        if(strcmp (Dir->d_name,".") ==0||strcmp (dir->d_name,"..") ==0)            {            Continue; } std::stringFull_path = path + dir->D_name; if(Lstat (Full_path.c_str (), &st) = =-1)        {            Continue; } std::stringName = Dir->D_name; //replace the blank char in name with "%$".         while(Name.find (" ")! = std::string:: NPOs) {Name.replace (Name.find (" "),1,"$%"); }        if(S_isdir (St.st_mode))//s_isdir () macro to determine if the directory file {name+="[d]";        Dir_name.push_back (name); }        Else{file_name.push_back (name);    }} closedir (DIRP);    Sort (File_name.begin (), File_name.end ());        Sort (Dir_name.begin (), Dir_name.end ());    Std::stringstream Ss_ret; intCount =0;  for(Auto I=dir_name.begin (); I!=dir_name.end (); i++) {Ss_ret<<*i; Count++; if(count%5==0) {Ss_ret<<Std::endl; }        Else{Ss_ret<<"  "; }    }         for(Auto I=file_name.begin (); I!=file_name.end (); i++) {Ss_ret<<*i; Count++; if(count%5==0)//five names per return. {Ss_ret<<Std::endl; }        Else{Ss_ret<<"  "; }} RET=Ss_ret.str (); return 0;}

  

Implementing the LS () function to traverse the directory under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.