【问题标题】:save readdir into a buffer in C将 readdir 保存到 C 中的缓冲区中
【发布时间】:2014-11-17 13:34:47
【问题描述】:

我正在使用readdir() 读取以输出目录中的所有文件。问题是我需要将字符串保存到缓冲区中。有没有办法将输出保存到缓冲区或文件描述符等中?

这是我的代码:

  DIR *directory;
  struct dirent *dir;

  directory = opendir();

  while ((dir = readdir(directory)) != NULL) {
    printf("%s\n", dir->d_name);
  }

  closedir(directory);

【问题讨论】:

  • 是的。但是你应该告诉我们更多你想要做什么。
  • 您可以将字符串复制到缓冲区而不是打印出来。
  • 它是服务器/客户端通信的一部分,我想将它保存到一定大小的缓冲区中(如果输入足够大,可能会有几个),然后发送。我不知道如何保存输入,这就是我问的原因:)

标签: c readdir


【解决方案1】:

使用scandir How to use scandir

它为你分配内存。这是一个例子

/**code to print all the files in the current directory **/
struct dirent **fileListTemp;
char *path = ".";//"." means current directory , you can use any directory path here
int noOfFiles = scandir(path, &fileListTemp, NULL, alphasort);
int i;
printf("total: %d files\n",noOfFiles);
for(i = 0; i < noOfFiles; i++){
    printf("%s\n",fileListTemp[i]->d_name);

您可以修改它以满足您的需要。另外不要忘记释放scandir分配的内存

【讨论】:

  • scandir() 有 5 个参数,而不是 4 个。如: int scandirat( int dirfd, const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *) , int (*compar)(const struct dirent **, const struct dirent **));
  • 我试图找到一个解决方案,说明如何将此方法的输出保存到字符缓冲区 [] 中。我用过strcat,这行得通,但我想我在某处读到这是一个糟糕的解决方案?这是正确的吗?
  • 另外,还有一个问题!是否可以从指定目录调用scandir?
  • 您是否尝试将所有元素存储在单个缓冲区中?
  • 是的,如果尺寸大于 500,或者(可能)几个。
【解决方案2】:

在这种情况下,您将不得不使用数据结构,例如链表或树。 这是一个简短的例子,一个可以研究的想法:

 pDir = readdir(directory);
 while ( pDir != NULL ){
   strcpy(dirStruct[iCtFile]->FileName, pp->d_name);
 }

展望未来,你应该考虑路径处理和其他问题。

【讨论】:

    【解决方案3】:

    请注意,您需要将目录名称传递给 opendir()

    这是一个简单的例子,说明如何读取它们并将它们保存到缓冲区中。每次达到极限时,它都会使指针翻倍。一旦进程死亡,现代操作系统将清理分配的内存。理想情况下,您还应该致电free() 以防出现故障。

    #include<stdio.h>
    #include <dirent.h>
    #include <sys/types.h>
    #include<string.h>
    #include<stdlib.h>
    
    int main(void)
    {
      size_t i = 0, j;
      size_t size = 1;
      char **names , **tmp;
      DIR *directory;
      struct dirent *dir;
    
      names = malloc(size * sizeof *names); //Start with 1
    
      directory = opendir(".");
      if (!directory) { puts("opendir failed"); exit(1); }
    
      while ((dir = readdir(directory)) != NULL) {
         names[i]=strdup(dir->d_name);
         if(!names[i]) { puts("strdup failed."); exit(1); }
         i++;
         if (i>=size) { // Double the number of pointers
            tmp = realloc(names, size*2*sizeof *names );
            if(!tmp) { puts("realloc failed."); exit(1); }
            else { names = tmp; size*=2;  }
         }
      }
    
      for ( j=0 ; j<i; j++)
      printf("Entry %zu: %s\n", j+1, names[j]);
    
      closedir(directory);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 1970-01-01
      • 2018-07-17
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 2019-03-27
      • 2023-04-10
      相关资源
      最近更新 更多