zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Xcode 6 下添加pch头文件
    兵器簿之github的配置和使用
    sql 2005性能调优
    C#遍历枚举(Enum)值
    使用 jQuery 调用 ASP.NET AJAX Page Method
    强制不使用“兼容性视图”的HTML代码
    HR在ERP实施过程中的作用
    WdatePicker日历添加事件,在任意月改变时处理日期事件
    JQuery实现表格自动增加行,对新行添加事件
    获取元素离文档各边的距离
  • 原文地址:https://www.cnblogs.com/horacle/p/13167762.html
Copyright © 2011-2022 走看看