问题与S_ISDIR()导致C(也许是因为STAT()没有正确设置它的结构?) [英] Issue with S_ISDIR() result in C (maybe because stat() isn't setting its struct properly?)

查看:761
本文介绍了问题与S_ISDIR()导致C(也许是因为STAT()没有正确设置它的结构?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的程序采取一个目录,然后打印该目录中的内容,并说明每个项目是否是一个目录或不。如果我给它包含文件F1.txt和F2.txt和文件夹的D1,D2和D3的目录,它应该打印:

I want my program to take a directory, then print the contents of that directory and state whether or not each item is a directory or not. If I give it a directory containing files F1.txt and F2.txt and folders D1, D2, and D3, it should print:

F1.txt不是目录结果
F2.txt不是目录结果
D1是目录结果
D2是目录结果
D3是目录

F1.txt is not directory
F2.txt is not directory
D1 is directory
D2 is directory
D3 is directory

char* curr[100];
DIR* dirp = opendir(name);
struct dirent* x;
struct stat fstat;

//go to each file til readdir gives NULL
while((x = readdir(dirp)) != NULL) {

  //store name of file
  curr[0] = (x -> d_name);

  //ignore files starting with "."
  if(*curr[0] == '.')
    continue;

  //set status
  stat(curr[0], &fstat);

  //print file name
  printf("%s", *curr);

  //check if it's a directory and print result
  if(S_ISDIR(fstat.st_mode))
    printf(" is directory\n");
  else
    printf(" is not directory\n");
}

这将打印说,所有的文件不是目录。如果我删除忽略开头的文件的一部分。它说F1.txt,F2.txt和D1的目录,而且,D2,D3,和..是目录(按顺序)。这让我觉得问题出在统计的呼叫,而不是我的使用宏,但我在这里感到困惑,所以我不知道pretty。

This prints saying that all the files are not directories. If I remove the part that ignores files starting with ".", it says F1.txt, F2.txt and D1 are not directories, and that ., D2, D3, and .. are directories (in that order). That makes me think the issue is with the stat call rather than my use of the macros, but I'm pretty confused here so I don't know.

推荐答案

您正在传递统计文件的名称,但它需要的文件的路径。如果您检查的返回值统计,你会看到,这只是成功的 .. ,因为他们中的任何目录中。

You're passing stat the name of the file, but it needs a path to the file. If you check the return value for stat, you'll see that it's only succeeding for . and .., because they exist in any directory.

典型的答案:永远不要试图去理解,通过错误条件刮起了程序的行为。只要它甚至哪怕一丁点神秘(最晚),加code,检查所有函数的返回值。

Canonical answer: Do not ever try to understand the behavior of a program that blows through error conditions. As soon as it's even the tiniest bit mysterious (at the latest), add code to check the return values of all functions.

这篇关于问题与S_ISDIR()导致C(也许是因为STAT()没有正确设置它的结构?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆