Simply error in C - folders explore
I got problem. Seriously i need help.
I directory SavedGames i got 5 folders
- aa
- bb
- lolgraa
- ffd
- zzzz
And here simply code in C to read what folders are in "SavedGames" and simly put in on screen.
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <windows.h>
int main (void)
{
DIR *dp;
struct开发者_StackOverflow中文版 dirent *ep;
char *array[4];
int i = 0;
dp = opendir ("SavedGames/");
while (ep = readdir (dp))
{
array[i++] = ep->d_name;
}
closedir (dp);
puts(array[0]);
puts(array[1]);
puts(array[2]);
puts(array[3]);
system("pause");
return 0;
}
It returns zzzz, zzzz, zzzz, zzzz, zzzz.
It seems this is simply error, but i spend on it 2 hour!! :( Thanks
You have forgotten to allocate memory space while storing the directories.
array[i] = (char*) malloc(strlen(ep->d_name) + 1);
strcpy(array[i], ep->d_name);
i++;
char *array[4];
is an array of 4 pointers to strings.
readdir
returns a structure containing pointers to strings, all of which is in (process) global memory, the next call to readdir
replaces the values present.
You are copying the pointer into your array, but that doesn't copy the string.
You need to copy the strings out of the struct dirent
, and allocate memory to store them in.
精彩评论