ppulse 2015-06-28 09:48 采纳率: 0%
浏览 1542

为什么在ubuntu下调用stat函数,执行路径不同,结果也会不同?

在ubuntu下编写判断一个文件是否目录得程序,调用了sys/stat.h头文件中得stat函数,生成可执行文件后,在不同路径下执行结果是不一样得,烦请各位大神帮忙看一下是什么情况,多谢多谢(没分额)。


说明:
在我得电脑上,程序存放得绝对路径是/home/xiaoming/Desktop/linuxStudy/filesystem/,执行程序时,分别在/home/xiaoming/Desktop/linuxStudy路径下执行和在程序存放路径下执行,得出得结果是不一样得。


代码:

#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>

int main()
{
    DIR *dir = opendir("/home/xiaoming/Desktop/linuxStudy");
    struct dirent *ptr;
    mode_t modes = 0;
    struct stat statbuf;
    while ((ptr = readdir(dir)) != NULL)
    {
        long offset = telldir(dir);        
        stat(ptr->d_name, &statbuf);
        modes = 0;
        modes = statbuf.st_mode;
        printf("statbuf.st_mode = %o\n", modes);
        if (S_ISDIR(modes))
            printf("------- %s is a dir\n", ptr->d_name);          
        else
            printf("******* %s is not a dir\n", ptr->d_name);
        printf("dirname: %s,  offset: %lx \n\n", ptr->d_name, offset);       
    }
    closedir(dir);
    exit(0);
}


执行结果:

图片说明
图片说明
图片说明

  • 写回答

1条回答 默认 最新

  • ppulse 2015-06-28 12:57
    关注

    经过实验,发现在readdir之前调用chdir,则不会出现这个问题,但原因仍未知。

    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏