cowchin12 cowchin12 - 4 years ago 112
C Question

CStoring strings into an array in c

I'm trying to read the files in a directory and store each file name in an array of strings. I can't get it to work for the life of me. Here's the function:

char *readFile(char *dir){
char *fileStringArray[1000];
DIR *dirPointer;
int file_count = 0;
struct dirent *file;
struct stat fileType;
int i = 0;
if ((dirPointer = opendir(dir)) == NULL){
printf("Directory not found, try again\n");
return NULL;
}else{
printf("Reading files in directory\n");
while((file = readdir(dirPointer)) != NULL){ //iterate through contents of directory
stat(dir, &fileType);
if(i > 1){ //ignore . and .. directories that appear first
file_count++;
printf("%s\n", file->d_name);
strcpy(fileStringArray[i-2], file->d_name); //crashes, replace
//with [i] to not crash, but i-2 makes more sense to me
//fileStringArray[i-2] = &file->d_name; alternate idea
}
else{
i++;
}
}
int j;
for(j = 0; j < file_count; j++){
printf(":::%s\n", fileStringArray[j]); //print the string array
}
}
printf("Done reading\n\n");
closedir(dirPointer);
return dir;
}

Answer Source

There are two issues with your code. Main one is that you try to store your strings in 1000 element array of pointers to chars. Pointer to char is not enough to store string, it actually need to point to some memory. You can solve it on many ways, consider changing your strcpy function to strdup - which will allocate memory for you. Or you need to change your fileStringArray to be array of array's of chars (char fileStringArray[1000][100]).

Second issue is with that i , you should increment it unconditionally if you actually want to advance in your array.

Also, it would be nice if you could post full example, so I don't have to guess headers to include.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download