• C++ 50行代码实现Linux ls -l 命令


    说明:此代码并不是实现完整的 ls 命令

    // filename:myls_l.cpp
    #include <iostream>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <pwd.h>
    #include <grp.h>
    #include <time.h>
    #include <string>
    
    int main(int argc, char *argv[])
    {
         using std::cout;
         using std::endl;
         using std::string;
         struct stat st;
         struct passwd *wd;
         struct group *gp;
         string tm;
         int ret = stat(argv[1], &st);
         if(ret == -1) { cout << "open error" << endl; return -1; }
         if(S_ISREG(st.st_mode))       cout << "-";
         else if(S_ISDIR(st.st_mode))      cout << "d";
         else if(S_ISCHR(st.st_mode))   cout << "c";
         else if(S_ISBLK(st.st_mode))   cout << "b";
         else if(S_ISLNK(st.st_mode))   cout << "l";
         else if(S_ISFIFO(st.st_mode))  cout << "f";
         else if(S_ISSOCK(st.st_mode))  cout << "s";
         if (st.st_mode & S_IRUSR)      cout << "r";
         else                   cout << "-";
         if (st.st_mode & S_IWUSR)      cout << "w";
         else                   cout << "-";
         if (st.st_mode & S_IXUSR)      cout << "x";
         else                   cout << "-";
         if (st.st_mode & S_IRGRP)      cout << "r";
         else                   cout << "-";
         if (st.st_mode & S_IWGRP)      cout << "w";
         else                   cout << "-";
         if (st.st_mode & S_IXGRP)      cout << "x";
         else                   cout << "-";
         if (st.st_mode & S_IROTH)      cout << "r";
         else                   cout << "-";
         if (st.st_mode & S_IWOTH)      cout << "w";
         else                   cout << "-";
         if (st.st_mode & S_IXOTH)      cout << "x";
         else                   cout << "-";
         cout << " " << st.st_nlink;
         wd = getpwuid(st.st_uid);
         cout << " " << wd->pw_name;
         gp = getgrgid(st.st_gid);
         cout << " " << gp->gr_name;
         cout << " " << st.st_size;
         tm = ctime(&st.st_mtime);
         cout << " " << tm.substr(4, 12);
         cout << " " << argv[1] << endl;
         return 0;
    }

    调用方法:

    $ g++ -o myls_l myls_l.cpp
    $ ./myls_l myls_l.cpp
  • 相关阅读:
    封装一个php语言的api提示类
    Content-Type四种常见取值
    postman中 form-data、x-www-form-urlencoded、raw、binary的区别
    ansible find
    Linux系统中根目录下或者新挂载的磁盘目录下有一个叫lost+found,它的作用是什么?
    rm /mv需要注意的
    mount
    es number_of_shards和number_of_replicas
    logstash设置配置路径
    ES7.8 设置 xpack
  • 原文地址:https://www.cnblogs.com/horacle/p/13167762.html
Copyright © 2020-2023  润新知