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 的功能,忽略隐藏文件。







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