【问题标题】:C - stat struct not working properly [duplicate]C - stat 结构无法正常工作[重复]
【发布时间】:2016-12-22 12:19:33
【问题描述】:

我正在尝试打印目录中文件的某些特征(仅以小写字母开头的文件)。但是,当我执行以下代码时,其中一些有效,有些无效。看起来 stat 结构可能无法正常工作,但到目前为止我还无法识别错误。

struct dirent *ep;
DIR *dp;    
char* cwd;
char buff[PATH_MAX + 1];
off_t tamTotal=0;
struct stat archivo;    
char path[]="/home/edu/Escritorio/P7/practica7/prueba";

if(!(dp=opendir(path))){
    printf("Error.\n");
    exit(-1);
}

printf("\nFILES:\n");
while (ep = readdir (dp)){ 
    stat(ep->d_name, &archivo);
    if(S_ISREG(archivo.st_mode)){
        if(!isupper(ep->d_name[0])){
            printf("  %s\n",ep->d_name);
            printf("    Last modification date: %s \n",ctime(&archivo.st_mtime));
            printf("    i-no number: %lu \n",archivo.st_ino);
            printf("    Blocks: %lu \n",archivo.st_blocks);
            printf("    Size: %lu \n",archivo.st_size);
        }       
    }
}   

输出:

【问题讨论】:

  • 你没有检查stat的返回值,那么你怎么知道它是否“正常工作”呢?我永远无法理解为什么人们决定省略错误检查,然后来到 Stack Overflow 询问他们的代码为什么表现异常。
  • 或许阅读stat并检查返回值会有所帮助
  • 确实,当我创建结构时它给了我一个错误。任何想法为什么?
  • if(!S_ISREG(... 的意思是“如果这不是一个常规文件”。
  • 这就是errno 会告诉你的。请使用perrorstrerror(errno)

标签: c file struct stat


【解决方案1】:

readdir 返回的 dirent 结构很可能只​​包含名称,而不包含目录或完整路径。

因此,stat 将失败,您不会注意到,因为您没有检查它的返回值。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2015-09-06
  • 2016-05-06
  • 2016-05-12
  • 2018-07-19
相关资源
最近更新 更多