当前位置:首页 > 通信资讯 > 正文

C语言telldir()函数:取得目录流的读取位置
头文件:

?
1 #include <dirent.h>

定义函数:

?
1 off_t telldir(DIR *dir);

函数说明:telldir()返回参数dir 目录流目前的读取位置. 此返回值代表距离目录文件开头的偏移量返回值返回下个读取位置, 有错误发生时返回-1.

错误代码:EBADF 参数dir 为无效的目录流。

范例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <sys/types.h> #include <dirent.h> #include <unistd.h> main() { DIR *dir; struct dirent *ptr; int offset; dir = opendir("/etc/rc.d"); while((ptr = readdir(dir)) != NULL) { offset = telldir (dir); printf("d_name : %s offset :%d\n", ptr->d_name, offset); } closedir(dir); }

执行结果:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 d_name : . offset :12 d_name : .. offset :24 d_name : init.d offset 40 d_name : rc0.d offset :56 d_name : rc1.d offset :72 d_name : rc2.d offset :88 d_name : rc3.d offset :104 d_name : rc4.d offset :120 d_name : rc5.d offset :136 d_name : rc6.d offset :152 d_name : rc offset :164 d_name : rc.local offset :180 d_name : rc.sysinit offset :4096

C语言seekdir()函数:设置下回读取目录的位置
头文件:

?
1 #include <dirent.h>

定义函数:

?
1 void seekdir(DIR * dir, off_t offset);

函数说明:seekdir()用来设置参数dir 目录流目前的读取位置, 在调用readdir()时便从此新位置开始读取. 参数offset 代表距离目录文件开头的偏移量。

错误代码:EBADF 参数dir 为无效的目录流。

范例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #include <sys/types.h> #include <dirent.h> #include <unistd.h> main() { DIR * dir; struct dirent * ptr; int offset, offset_5, i = 0; dir = opendir("/etc/rc.d"); while((ptr = readdir(dir)) != NULL) { offset = telldir(dir); if(++i == 5) offset_5 = offset; printf("d_name : %s offset :%d \n", ptr->d_name, offset); } seekdir(dir offset_5); printf("Readdir again!\n"); while((ptr = readdir(dir)) != NULL) { offset = telldir(dir); printf("d_name : %s offset :%d\n", ptr->d_name, offset); } closedir(dir); }

执行:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 d_name : . offset :12 d_name : .. offset :24 d_name : init.d offset 40 d_name : rc0.d offset :56 d_name : rc1.d offset :72 d_name : rc2.d offset :88 d_name : rc3.d offset :104 d_name : rc4.d offset :120 d_name : rc5.d offset :136 d_name : rc6.d offset :152 d_name : rc offset :164 d_name : rc.local offset :180 d_name : rc.sysinit offset :4096 readdir again! d_name : rc2.d offset :88 d_name : rc3.d offset :104 d_name : rc4.d offset :120 d_name : rc5.d offset :136 d_name : rc6.d offset :152 d_name : rc offset :164 d_name : rc.local offset :180 d_name : rc.sysinit offset :4096
如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。