歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> linux系統編程之文件與I/O(三) 目錄的操作

linux系統編程之文件與I/O(三) 目錄的操作

日期:2017/3/3 16:24:25   编辑:關於Linux

一、目錄的訪問

功能說明:打開一個目錄

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

返回值:

打開成功,返回一個目錄指針

打開失敗,則返回NULL

功能說明:訪問指定目錄中下一個連接的細節

原型:struct dirent* readdir(DIR *dirptr);

返回值:

返回一個指向dirent結構的指針,它包含指定目錄中下一個連接的細節;

沒有更多連接時,返回NULL

功能說明:關閉一個已經打開的目錄

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

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

功能說明:用來創建一個稱為pathname的新目錄,它的權限位設置為mode

原型:int mkdir(char *pathname,mode_t mode);

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

功能說明:刪除一個空目錄

原型:int rmdir(char *pathname);

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

功能說明:用來改變給定路徑名pathname的文件的權限位

原型:int chmod (char *pathname, mode_t mode);

int fchmod (int fd, mode_t mode);

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

功能說明:用來改變文件所有者的識別號(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

示例程序:

/*************************************************************************
> File Name: file_ls.c
> Author: Simba
> Mail: [email protected]
> Created Time: Sat 23 Feb 2013 02:34:02 PM CST
************************************************************************/
#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 的功能,忽略隱藏文件。

Copyright © Linux教程網 All Rights Reserved