與目錄相關的有:
#include<dirent.h>
(1)DIR *opendir(const char *pathname);
打開一個目錄,並且返回一個DIR類型的指針
(2)struct dirent *readdir(DIR *dp);
讀一個目錄並且返回一個dirent類型的指針。
(3)void rewinddir(DIR *dp);
(4)long telldir(DIR *dp);
(5)void seekdir(DIR *dp,long loc);
與目錄操作有關的結構體有:
dirent結構體:
struct dirent {
ino_t d_ino; /* 索引號 */
off_t d_off; /* 下一個偏移量 */
unsigned short d_reclen; /* 本記錄長度 */
unsigned char d_type; /* 文件類型 */
char d_name[256]; /* 文件名 */
};
DIR結構體
struct __dirstream
{
void *__fd; /* `struct hurd_fd' pointer for descriptor. */
char *__data; /* Directory block. */
int __entry_data; /* Entry number `__data' corresponds to. */
char *__ptr; /* Current pointer into the block. */
int __entry_ptr; /* Entry number `__ptr' corresponds to. */
size_t __allocation; /* Space allocated for the block. */
size_t __size; /* Total valid data in the block. */
__libc_lock_define (, __lock) /* Mutex lock for this structure. */
};
typedef struct __dirstream DIR;
應用上面的所有知識可以解決有關目錄操作的所有問題了。下面寫了一個簡單的程序來說明相關函數的應用:
題目:給定一個目錄,然後遍歷目錄下面所有的文件,並打印文件名
#include<dirent.h>
#include<stdio.h>int main(int argc,char **argv)
{
DIR *dirp;
struct dirent *direntp;
if(argc!=2)
{
printf("formant error!\n");
}
dirp=opendir(argv[1]);
while((direntp=readdir(dirp))!=NULL)
{
printf("%s\n",direntp->d_name);
}
close(dirp);
exit(0);
}