Implement Ls-l

Source: Internet
Author: User

is to traverse all the files under a directory to display the information

Linux is a bit around here.

To open the directory via Opendir, return a DIR structure

Use Readdir to read the DIR structure, return the first item under the directory, is a dirent struct, call Readdir again to read the second item, and so on

The dirent structure contains the file name of the file, and the details of the file can be obtained through stat.

Pay attention to the stat structure to malloc, no, then segment fail?? It seems to be the word. If there is no allocation, the pointer will be randomly pointed.

Read and write execution permissions in mode_t, there is no direct output of the function, to write a self, to determine whether there is no such permission, with the operation, not sentenced and so on.

The rest of the information is in stat, which only outputs the St_mode.

#include <dirent.h>#include<stdio.h>#include<sys/stat.h>#include<fcntl.h>voidShow (mode_t mode) {if(mode&s_irusr) printf ("R"); Elseprintf ("-"); if(mode&s_iwusr) printf ("W"); Elseprintf ("-"); if(mode&s_ixusr) printf ("x"); Elseprintf ("-"); /*********group********/    if(mode&s_irgrp) printf ("R"); Elseprintf ("-"); if(mode&s_iwgrp) printf ("W"); Elseprintf ("-"); if(mode&s_ixgrp) printf ("x"); Elseprintf ("-"); /**********else***************/    if(mode&s_iroth) printf ("R"); Elseprintf ("-"); if(mode&s_iwoth) printf ("W"); Elseprintf ("-"); if(mode&s_ixoth) printf ("x"); Elseprintf ("-"); printf ("\ n");}intMainintargcChar*argv[]) {DIR*DP; structdirent*dir; structStat * BUF = (structStat *)malloc(sizeof(structstat)); intFD; DP= Opendir (argv[1]);  while(dir = Readdir (DP))! =NULL) {printf ("%s",dir->d_name); //fd = open (DIR->D_NAME,O_RDWR); //Fstat (FD,BUF);Stat (dir->d_name,buf); Show (Buf-St_mode); } printf ("DONE !!!! \ n"); }

Implement Ls-l

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.