Linux系統編程:目錄的操作

一、目錄的訪問


1.功能說明:打開一個目錄

原型:DIR*  opendir(char *pathname);

返回值:
打開成功,返回一個目錄指針
打開失敗,則返回NULL


2.功能說明:訪問指定目錄中下一個連接的細節
原型:struct  dirent*  readdir(DIR  *dirptr);

返回值:
返回一個指向dirent結構的指針,它包含指定目錄中下一個連接的細節;
沒有更多連接時,返回NULL


3.功能說明:關閉一個已經打開的目錄
原型:int closedir (DIR  *dirptr);

返回值:調用成功返回0,失敗返回-1


二、目錄信息結構體

  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 */
 };


三、目錄的創建刪除和權限設置


1.

功能說明:用來創建一個稱爲pathname的新目錄,它的權限位設置爲mode
原型:int  mkdir(char *pathname,mode_t mode);

返回值:調用成功返回0,失敗返回-1

mkdir常犯錯誤是認爲權限爲0666和文件相同,通常來說目錄是 需要可執行權限,不然我們不能夠在下面創建目錄。


2.

功能說明:刪除一個空目錄
原型:int  rmdir(char *pathname);

返回值:調用成功返回0,失敗返回-1


3.

功能說明:用來改變給定路徑名pathname的文件的權限位
原型:int  chmod (char *pathname, mode_t mode);

int  fchmod (int  fd, mode_t mode);

返回值:調用成功返回0,失敗返回-1


4.

功能說明:用來改變文件所有者的識別號(owner id)或者它的用戶組識別號(group ID)
原型:int  chown (char *pathname, uid_t owner,gid_t group);

int  fchown (int  fd, uid_t owner,gid_t group);

返回值:調用成功返回0,失敗返回-1


#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<dirent.h>

#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)

int main(int argc, char *argv[])
{
    DIR *dir = opendir(".");
    struct dirent *de;
    while ((de = readdir(dir)) != NULL)
    {
        if (strncmp(de->d_name, ".", 1) == 0)
            continue; //忽略隱藏文件
        printf("%s\n", de->d_name);
    }

    closedir(dir);
    exit(EXIT_SUCCESS); // 等價於return 0
}
以上程序將當前目錄的文件名進行輸出,類似 ls 的功能,忽略隱藏文件。







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章