文件和目錄

學習筆記,小白可以相互學習,大佬看到能告訴咱理解不對的地方就好了。


函數

1.stat

獲取文件/目錄屬性信息

 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 int stat(const char *path, struct stat *buf);     //主要掌握這一個,函數返回一個與此命名有關的信息結構
 int fstat(int fd, struct stat *buf);
 int lstat(const char *path, struct stat *buf);

           struct stat {
               dev_t     st_dev;     /* ID of device containing file */
               ino_t     st_ino;     /* inode number */
               mode_t    st_mode;    /* protection */
               nlink_t   st_nlink;   /* number of hard links */
               uid_t     st_uid;     /* user ID of owner */
               gid_t     st_gid;     /* group ID of owner */
               dev_t     st_rdev;    /* device ID (if special file) */
               off_t     st_size;    /* total size, in bytes */
               blksize_t st_blksize; /* blocksize for file system I/O */
               blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
               time_t    st_atime;   /* time of last access */
               time_t    st_mtime;   /* time of last modification */
               time_t    st_ctime;   /* time of last status change */
           };

        struct passwd *uid = getpwuid(b.st_uid); //獲得用戶名
        struct group *gid = getgrgid(b.st_gid);//獲得所屬組名

        struct tm *t = localtime(&b.st_ctime);//獲取時間
        printf("%2d月,%2d日,%2d點,%2d分,%2d秒  ",t->tm_mon,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);



/**************自己寫的實現ls -l功能*******************************/

#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<dirent.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
int main()
{
    DIR *f = opendir(".");
    struct dirent *r;
    struct stat b;
    while( r = readdir(f) )
    {
        if( 0 > stat(r->d_name,&b))
        {
            perror("stat");
            return -1;
        }
        struct passwd *uid = getpwuid(b.st_uid); //獲得用戶名
        struct group *gid = getgrgid(b.st_gid);//獲得所屬組名
        printf("userID:%s  ",uid->pw_name);
        printf("groupID:%s  ",gid->gr_name);
        
        //******************文件類型**************
        switch(b.st_mode & S_IFMT)//文件類型的位遮罩S_TFMT
        {
            case S_IFREG:
                printf("-");
                break;
            case S_IFDIR:
                printf("d");
                break;
            case S_IFCHR:
                printf("c");
                break;
            case S_IFBLK:
                printf("b");
                break;
            case S_IFIFO:
                printf("p");
                break;
            case S_IFLNK:
                printf("c");
                break;
            case S_IFSOCK:
                printf("s");
                break; 
        }
//***********************文件的權限**************
        (b.st_mode & S_IRUSR?printf("r"):printf("-"));
        (b.st_mode & S_IWUSR?printf("w"):printf("-"));
        (b.st_mode & S_IXUSR?printf("x"):printf("-"));
        (b.st_mode & S_IRGRP?printf("r"):printf("-"));
        (b.st_mode & S_IWGRP?printf("w"):printf("-"));
        (b.st_mode & S_IXGRP?printf("x"):printf("-"));
        (b.st_mode & S_IROTH?printf("r"):printf("-"));
        (b.st_mode & S_IWOTH?printf("w"):printf("-"));
        (b.st_mode & S_IXOTH?printf("x  "):printf("-  "));

        //**********文件大小************************
        printf("%5ld  ",b.st_size);

        //************時間*******************************
        struct tm *t = localtime(&b.st_ctime);
        printf("%2d月,%2d日,%2d點,%2d分,%2d秒  ",t->tm_mon,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);

//************文件名字***************
        printf("%s",r->d_name);

        printf("\n");
    }
    
    closedir(f);
    return 0;
}


/*******************標準點的********************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

void getfiletype(mode_t m, char *type)
{
	if (S_ISREG(m)) 
		*type = '-';
	else if (S_ISDIR(m))
		*type = 'd';
	else if (S_ISCHR(m))
		*type = 'c';
	else if (S_ISBLK(m))
		*type = 'b';
	else if (S_ISFIFO(m))
		*type = 'p';
	else if (S_ISLNK(m))
		*type = 'l';
	else if (S_ISSOCK(m))
		*type = 's';
}

void getfilemode(mode_t m, char *mode)
{
	if (m & S_IRUSR)
		mode[0] = 'r';
	if (m & S_IWUSR)
		mode[1] = 'w';
	if (m & S_IXUSR)
		mode[2] = 'x';

	if (m & S_IRGRP)
		mode[3] = 'r';
	if (m & S_IWGRP)
		mode[4] = 'w';
	if (m & S_IXGRP)
		mode[5] = 'x';
	
	if (m & S_IROTH)
		mode[6] = 'r';
	if (m & S_IWOTH)
		mode[7] = 'w';
	if (m & S_IXOTH)
		mode[8] = 'x';
}

void getfileusrname(uid_t uid, char *usrname)
{
	struct passwd *pw = getpwuid(uid);
	strcpy(usrname, pw->pw_name);
}

void getfilegrpname(gid_t gid, char *grpname)
{
	struct group *grp = getgrgid(gid);
	strcpy(grpname, grp->gr_name);
}

void getfiletime(time_t ctime, char *filetime)
{
	struct tm *tm = localtime(&ctime);
	sprintf(filetime, "%2d月 %2d %2d:%2d", tm->tm_mon+1, tm->tm_mday, \
			tm->tm_hour, tm->tm_min);
}

int main()
{
	DIR *dirp = opendir(".");
	struct dirent *file;
	struct stat buf;
	while (file = readdir(dirp)) {
		if (0 > stat(file->d_name, &buf)) {
			perror("stat");
			break;
		}
		char type;
		getfiletype(buf.st_mode, &type);
		char mode[9] = {0};
		memset(mode, '-', sizeof(mode));
		getfilemode(buf.st_mode, mode);
		char usrname[10];
		getfileusrname(buf.st_uid, usrname);
		char grpname[10];
		getfilegrpname(buf.st_gid, grpname);
		char filetime[20];
		getfiletime(buf.st_ctime, filetime);
		fprintf(stdout, "%c%9s %2d %10s %10s %6ld %15s %s\n", type, mode, buf.st_nlink, usrname, grpname, buf.st_size, filetime, file->d_name);
	}

	return 0;
}

2.opendir

打開目錄

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);

成功返回DIR*類型的目錄流,失敗返回NULL


3.readdir

讀取目錄

#include <dirent.h>
struct dirent *readdir(DIR *dirp);

成功返回下個目錄進入點,失敗或者到達目錄文件尾返回NULL

struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* offset to the next dirent */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                                              by all file system types */
               char           d_name[256]; /* filename */
                      };

DIR *f = opendir(".");//打開當前目錄
struct dirent *r;
struct stat b;
while(r = readdir(f)) //讀取目錄

{printf("%s",r->d_name);}//目錄下的成員名


4.closedir

關閉目錄

#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);

關閉成功返回0,失敗返回-1,並設置errno

發佈了31 篇原創文章 · 獲贊 21 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章