Linux中的stat函数只能访问当前用户所在目录(提示stat-No such file or directory错误)

在Linux C编程中,stat函数在递归读取目录时出现'No such file or directory'错误。问题源于对stat函数的理解不准确,它需要路径中所有目录具有执行权限。错误在于使用了相对路径而非绝对路径。修正代码后,确保使用绝对路径来获取文件的stat状态。
摘要由CSDN通过智能技术生成

问题介绍

最近使用Linux C进行编程的时候,当递归读取目录的时候会发现stat函数一直再报错(No such file or directory),经过一晚上的修改bug,发现我的代码中的stat函数只能访问用户当前所在的路径下的文件(即’pwd‘命令所提示的目录)。

例如:此时我所在的路径为:/home/mrzhi/Desktop/Linux-网络编程/Unix_systems_programming/Chapter5_File_system

结果:可以发现该代码可以正确访问所在路径下的文件,但是该路径下的文件夹却无法递归访问。但是该代码中的opendir和reddir函数可以正确打开和读取该路径下的文件夹。但是却无法使用stat函数返回文件的属性。

图1. 结果描述

问题分析

这里我们先查看一下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 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值