c - 在 C 2.0 统计错误中读取目录

标签 c list path directory stat

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

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 {...}

最佳答案

只需将从 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);
  }
}

关于c - 在 C 2.0 统计错误中读取目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382153/

相关文章:

Java NIO 路径 : getting the base path from a full path?

c - 如何使用 C 中的宏访问作为二维数组的 int 指针?

c - 对数组进行排序,使偶数先降序出现,然后赔率升序出现

python - 如何通过python计算属于字符串列表的每个字符串长度?

python setup.py install 更改脚本解释器

javascript - 更改模块路径

应用程序中是否可以存在相同库(具有相同名称)的两个不同版本?

c - long int 参数 != long int 参数

python - 是什么导致这个 return() 创建一个语法错误?

python - 在不使用 itertools 的情况下查找嵌套列表的总和