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
  • 相关阅读:
    Excel Sheet Column Number
    HappyNum
    isIsomorphic
    Contains DuplicateII
    iis7 设置http 自动跳转到https
    php 安装redis
    java 打包 war包
    NPOI 操作excel之 将图片插入到指定位置;
    nopi 简洁笔记
    vs11 微软下载地址
  • 原文地址:https://www.cnblogs.com/horacle/p/13167762.html
Copyright © 2011-2022 走看看