问题介绍
最近使用Linux C进行编程的时候,当递归读取目录的时候会发现stat函数一直再报错(No such file or directory),经过一晚上的修改bug,发现我的代码中的stat函数只能访问用户当前所在的路径下的文件(即’pwd‘命令所提示的目录)。
例如:此时我所在的路径为:/home/mrzhi/Desktop/Linux-网络编程/Unix_systems_programming/Chapter5_File_system
结果:可以发现该代码可以正确访问所在路径下的文件,但是该路径下的文件夹却无法递归访问。但是该代码中的opendir和reddir函数可以正确打开和读取该路径下的文件夹。但是却无法使用stat函数返回文件的属性。
问题分析
这里我们先查看一下stat函数的定义
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
/* These functions return information about a file, in the buffer pointed to by statbuf.
No permissions are required on the file itself, **but—in the case of stat(), fstatat(),
and lstat()—execute (search) permission is required on all of the directories in pathname that lead to the file.**
* stat() and fstatat() retrieve information about the file pointed to by pathname;
the differences for fstatat() are described below.
*/
可以发现其中有这样一句话:but——in the case of stat, fstatat(), and lstat() - execute (search) permission is required on all of the directories in pathname that lead to the file。
这句话的意思是路径名中指向该文件的所有目录都必须具有执行(搜索权限)。也就是我所在目录下的test必须具备执行或搜索权限。
错误原因:
只有文件为绝对路径的情况下,才可以获取文件的stat状态。而刚开始的代码中直接为./test/bbb.txt,此时pathname会直接访问根目录下的test/bbb.txt,但是我的根目录下没有这个文件,因此会报“No Such file or directory”的错误。要切记使用绝对路径。
代码示例
我的代码示例如下:
**// 这个一个使用opendir,readdir和closedir等对目录操作的函数
// 该程序显示的是目录中包含的文件名,其实这个目录的路径名被作为命令行参数传送
// note:ls命令会按照字母顺序对文件名进行排序,而readdir函数则按照起在目录文件中出现的顺序显示文件名
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include