实现“ls -l 文件名“功能

DIR *opendir(const char *name);

功能:获得目录流

参数:要打开的目录

返回值:成功:目录流

失败:NULL

struct dirent *readdir(DIR *dirp);

功能:读目录

参数:要读的目录流

返回值:成功:读到的信息

失败或读到目录结尾:NULL

返回值为结构体,该结构体成员为描述该目录下的文件信息

struct dirent {

ino_t d_ino; /* 索引节点号*/

off_t d_off; /*在目录文件中的偏移*/

unsigned short d_reclen; /* 文件名长度*/

unsigned char d_type; /* 文件类型 */

char d_name[256]; /* 文件名 */

};

#include
#include
#include
#include
#include
#include
#include

int main(int argc, char const *argv[])
{
    struct stat s;
    if (stat("ccc.c", &s) < 0)
    {
        perror("stat err");
        return -1;
    }
    printf("%lu\n", s.st_ino);

    printf("%lu\n", s.st_size);

    printf("%#o\n", s.st_mode);
   

    switch (s.st_mode & S_IFMT) //判断文件类型
    {
    case S_IFSOCK:
        printf("s");
        break;
    case S_IFCHR:
        printf("c");
        break;
    case S_IFLNK:
        printf("l");
        break;
    case S_IFREG:
        printf("-");
        break;
    case S_IFBLK:
        printf("b");
        break;
    case S_IFDIR:
        printf("d");
        break;
    case S_IFIFO:
        printf("p");
        break;
    }

  char buf[4]="rwx-";//判断文件权限
    for(int i =0;i<9;i++)
    {
        printf("%c",(s.st_mode& (0400>>i))? buf[i%3]:buf[3])

    }

    printf(" %d", s.st_nlink); //硬链接数


    //用户和组
    struct passwd *p; //用户
    p = getpwuid(s.st_uid);
    printf(" %s", p->pw_name);

    struct group *q; //组
    q = getgrgid(s.st_gid);
    printf(" %s", q->gr_name);

    printf(" %ld", s.st_size); //查看大小

    struct tm *now_time;//最后访问时间
    now_time = localtime(&s.st_mtime);
    printf(" %d-%d-%d %d:%d", now_time->tm_year + 1900,
           now_time->tm_mon + 1,
           now_time->tm_mday, now_time->tm_hour,
           now_time->tm_min);

    printf("%s ","  ccc.c");//打印文件名

你可能感兴趣的:(c++,数据结构,算法)