10Linux服务器编程之:opendir()函数,readdir()函数,rewinddir()函数,telldir()函数和seekdir()函数,closedir()函数
1 opendir所需的頭文件
#include<sys/types.h>
#include<dirent.h>
2函數聲明
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
通過opendir來打開一個文件夾
3readdir依賴的頭文件
#include<dirent.h>
4函數聲明
struct dirent *readdir(DIR *dirp);
int readdir_r(DIR *dirp, struct dirent*entry, struct dirent **result);
函數說明
通過這兩個函數實現讀取目錄
關于struct dirent,定義如下:
struct dirent {
????ino_t? d_ino;?????? ??????/* inode number */
????off_t? d_off;?????? ??????/* not an offset; see NOTES */
???? unsignedshort d_reclen;??? /* length of this record*/
????unsigned char d_type;????? /* typeof file; not supported
???? ????????????????????????by all filesystem types */
????char d_name[256];?????? ?/* filename */
};
readdir每次返回一條記錄項,DIR*指針指向下一條記錄項
6.rewinddir
#include <sys/types.h>
#include <dirent.h>
void rewinddir(DIR *dirp);
把目錄指針恢復到目錄的起始位置。
7.telldir/seekdir
#include <dirent.h>
long telldir(DIR *dirp);
#include <dirent.h>
void seekdir(DIR *dirp, long offset);
?
函數描述
telldir - return current location indirectory stream
?
The? telldir()?function returns the current location associated with
?????? the directory stream dirp.
?
8.closedir
#include<sys/types.h>
#include<dirent.h>
int closedir(DIR*dirp);
函數描述
The? closedir()?function closes the directory stream associated with
?????? dirp.?A successful call to closedir()?also? closes? the?underlying
?????? file?descriptor associated with dirp.?The directory stream descrip‐
?????? tor dirp is not available after thiscall.
?
9.通過遞歸的方式遍歷目錄
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
#include<stdio.h>
#include<string.h>
#define MAX_PATH1024
/* dirwalk: applyfcn to all files in dir */
void dirwalk(char*dir, void (*fcn)(char *))
{
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if ((dfd = opendir(dir)) == NULL) {
fprintf(stderr, "dirwalk: can't open%s\n", dir);
return;
}
while ((dp = readdir(dfd)) != NULL) {
if (strcmp(dp->d_name, ".") ==0
|| strcmp(dp->d_name, "..") ==0)
continue; /* skip self and parent */
if (strlen(dir)+strlen(dp->d_name)+2> sizeof(name))
fprintf(stderr, "dirwalk: name %s %stoo long\n",
dir, dp->d_name);
else {
sprintf(name, "%s/%s", dir,dp->d_name);
(*fcn)(name);
}
}
closedir(dfd);
}
?
/* fsize: printthe size and name of file "name" */
void fsize(char*name)
{
struct stat stbuf;
if (stat(name, &stbuf) == -1) {
fprintf(stderr, "fsize: can't access%s\n", name);
return;
}
if ((stbuf.st_mode & S_IFMT) ==S_IFDIR)
dirwalk(name, fsize);
printf("%8ld %s\n",stbuf.st_size, name);
}
?
int main(intargc, char **argv)
{
if (argc == 1) /* default: currentdirectory */
fsize(".");
else
while (--argc > 0)
fsize(*++argv);
return 0;
}
這個程序還是不如ls -R健壯,它有可能死循環,思考一下什么情況會導致死循
環。
總結
以上是生活随笔為你收集整理的10Linux服务器编程之:opendir()函数,readdir()函数,rewinddir()函数,telldir()函数和seekdir()函数,closedir()函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开具收入证明有哪些误区
- 下一篇: 关系再好,这些事也不能跟同事说,切记!