【问题标题】:reading directories in C 2.0 stat error在 C 2.0 stat 错误中读取目录
【发布时间】:2014-02-18 08:49:48
【问题描述】:

我想列出一个目录中的档案,它可以工作。问题是如果我在“。”我想在“./hello”中列出 te 文件,因为“.”,(ls -l hello)例如。问题是我不知道如何将完整路径添加到 stat 中,有人可以帮我吗?我有这个代码:

else if(strcmp(O->argv[1], "-l")==0){
  if(O->argv[2]==NULL){
      dir=getcwd(buffer,256);
      printf("%s \n",dir);
  }
  else {
     dir=getcwd(buffer,256);
     strcat(dir,"/");
     strcat(dir,O->argv[2]);
     printf("%s \n",dir);
  }
  if ((pdirectorio=opendir(dir)) == NULL) //abrir directorio
    printf("Error al abrir el directorio\n");
  else {
    while((directorio=readdir(pdirectorio))!= NULL){
       if((stat(directorio->d_name,&info)) == -1)
          printf("Fin de directorio.\n");
      else {...}

【问题讨论】:

    标签: c list path directory stat


    【解决方案1】:

    只需将您从 readdir() 获得的文件名连接到您正在遍历的目录的名称。大致如下:

    #include <stdio.h>
    #include <string.h>
    #include <dirent.h>
    #include <sys/stat.h>
    
    #define PATH_MAX 1024
    
    int main(int argc, char **argv) {
      DIR *d;
      struct dirent *e;
      char fullpath[PATH_MAX];
      struct stat st;
    
      if(argc > 1) {
        if((d = opendir(argv[1])) == NULL) return 1;
      } else
        return 2;
    
      while ((e = readdir(d)) != NULL) {
        snprintf(fullpath, PATH_MAX, "%s/%s", argv[1], e->d_name);
        if((stat(fullpath, &st)) == 0)
          printf("Did stat(%s) and got block count %u.\n",
            fullpath, st.st_blocks);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-02
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多