문제

I want to list a folder but when I want to print the filename only \n are print

void    liste_folder(void)
{
  DIR           *dir;
  struct dirent *test;

  dir = opendir(".");
  while (readdir(dir) != NULL)
    {
      test = malloc(sizeof(*test));
      printf("%s\n", test->d_name);
      free(test);
    }
}

int     main()
{
  liste_folder();
}
도움이 되었습니까?

해결책

You're allocating memory for test, but that doesn't fill it with the directory info. readdir allocates the memory for the dirent structure for you, so it isn't even necessary. Assign the return-value of readdir to test instead:

while((test = readdir(dir)) != NULL){
    printf("%s\n", test->d_name);
    // the man page says you may not free the dirent
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top