This program is used to follow the ls-l command in linux. The main functions used include opendir, readdir, and lstat. The Code is as follows:
# Include <iostream> # include <vector> # include <cstdlib> # include <dirent. h> # include <sys/types. h> # include <sys/stat. h> # include <unistd. h >#include <cstring >#include <algorithm> using namespace std; void getFileAndDir (vector <string> &, char *); void displayFileDistribute (vector <string> &); int main (int argc, char * argv []) {vector <string> file; if (argc! = 2) {cerr <"usage: ls/XXX" <endl; exit (1);} getFileAndDir (file, argv [1]); displayFileDistribute (file ); /* vector <string >:: iterator it = file. begin (); for (; it! = File. end (); ++ it) {// cout <* it <endl;} */exit (0);} void getFileAndDir (vector <string> & file, char * dirName) {DIR * dir; struct dirent * drt; dir = opendir (dirName); if (dir = NULL) {cerr <"cann' t opendir" <dirName <endl; exit (1) ;}while (drt = readdir (dir ))! = NULL) {// cout <drt-> d_name <endl; if (! Strcmp (drt-> d_name, ".") |! Strcmp (drt-> d_name ,".. ") {continue;} file. push_back (drt-> d_name);} closedir (dir);} void displayFileDistribute (vector <string> & file) {vector <string >:: iterator it = file. begin (); struct stat filestat; string perm [] = {"---", "-- x", "-w-", "-wx", "r --", "r-x", "rw-", "rwx"}; cout <"Total" <file. size () <endl; sort (file. begin (), file. end (); for (; it! = File. end (); ++ it) {if (lstat (* it ). c_str (), & filestat) =-1) {cerr <"stat filed! "<Endl; continue;} cout <filestat. st_ino <"; // inodeif (S_ISREG (filestat. st_mode) cout <"-"; else if (S_ISDIR (filestat. st_mode) cout <"d"; else if (S_ISCHR (filestat. st_mode) cout <"c"; else if (S_ISBLK (filestat. st_mode) cout <"B"; else if (S_ISFIFO (filestat. st_mode) cout <"p"; else if (S_ISLNK (filestat. st_mode) cout <"l"; else if (S_ISSOCK (filestat. st_mode) cout <"s"; elsecout <"X"; // get permint I = 3; unsigned int mask = 0700; while (I> 0) {cout <perm [(filestat. st_mode & mask) >>( I-1) * 3]; -- I; mask >>>= 3 ;}cout <"<filestat. st_uid <"; cout <filestat. st_gid <"; string str = ctime (& filestat. st_atime); cout <str. substr (0, str. length ()-9) <""; cout <* it <endl ;}}
Compile and run the Code: The program needs to receive a DIRECTORY parameter such./Ls/home/wyp