简体   繁体   English

将readdir保存到C中的缓冲区

[英]save readdir into a buffer in C

I'm using readdir() to read to output all the files in a directory. 我正在使用readdir()读取以输出目录中的所有文件。 The problem is that I need to save the strings into a buffer. 问题是我需要将字符串保存到缓冲区中。 Is there any way to save the output into a buffer or file descriptor etc? 有什么方法可以将输出保存到缓冲区或文件描述符等中?

Here is my code: 这是我的代码:

  DIR *directory;
  struct dirent *dir;

  directory = opendir();

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

  closedir(directory);

In this case you will have to work with a data structure, like a linked list or a tree. 在这种情况下,您将必须使用数据结构,例如链表或树。 Here's a short example, an idea to work on: 这是一个简短的示例,一个可行的想法:

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

Looking ahead, you should consider path treatment and other issues. 展望未来,您应该考虑路径处理和其他问题。

Note that you'll need to pass a directory name to opendir() . 请注意,您需要将目录名称传递给opendir()

This is simple example of how to read and save them into a buffer. 这是有关如何读取它们并将其保存到缓冲区的简单示例。 It doubles the pointers every time it hits the limit. 每次达到极限时,指针都会加倍。 Modern operating systems will clean up the memory allocated once process dies. 一旦进程终止,现代操作系统将清理分配的内存。 Ideally, you should also call free() in case of failures. 理想情况下,如果发生故障,您还应该调用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);
}

Use scandir How to use scandir 使用scandir 如何使用scandir

It allocates the memory for you. 它为您分配内存。 Here is an example 这是一个例子

/**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);

you can modify it to suit your need . 您可以根据需要进行修改。 Also do not forget to free memory allocated by scandir 也不要忘记释放scandir分配的内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM