I've honestly no idea what is going on here but here is my explanation>
I malloc an array of strings for holding an array of filenames, no problem there. I then move into a while loop where it keeps all the correct values until it hits this to print the time
time(&rawtime);
printf("It is now: %s\n\n",ctime(&rawtime));
Then my values are gone. Can't find them anywhere, I seem to now have an empty array.
Here is the rest of the code
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i,j, directSize,start=0,flag=0, menu;
size_t size;
char path[1024]; //current working directory path
char ** files; //created to store the directory contents in an array of strings
char buffer ; //buffer holds menu selection
time_t rawtime;
//buffer = (char*) malloc(sizeof(char));
files = (char**) malloc(sizeof(char*)+1);
//allocating memory for strings
for(i=0;i<50;i++)
{
files[i] =(char*) malloc(64*sizeof(char));
}
getcwd(path,size);
pid_t child;
DIR * d;
struct dirent *de;
d = opendir(".");
i=0;
while((de = readdir(d)))
{
files[i] = de->d_name;
i++;
}
directSize = i;
closedir(d);
printf("file[0]: %s",files[0]);
while(flag == 0)
{
printf("\nfiles[0]: %s\n",files[0]); //works
printf("Current Working directory: %s\n", path);
printf("\nfiles[0]: %s\nSize: %d\n",files[0],directSize); //works
time(&rawtime);
printf("It is now: %s\n\n",ctime(&rawtime)); //problem area?
printf("files[0]: %s\nSize: %d\n",files[0],directSize); //doesn't work
printf("Files:\t\t0. (..)\n");
for(i=start;i<start+4;i++)
printf("\t\t%d. %s \n",i+1, files[i]);
//formatted print for the command menu
printf("\nOperation:\tV View\n\t\tR Run\n\t\tP Previous Files\tN Next Files\n\t\tX Exit\t\t\tH Help\n");
printf("\nCommand: ");
scanf("%c", &buffer);
getchar();
//if(isalpha(buffer))
// strcpy(buffer,toupper(buffer));
printf("command chosen is: %c\n",buffer);
//if(buffer != "N" && buffer != "P" && buffer != "X")
//{
// printf("File/Directory #: ");
// scanf("%d", &menu);
//}
if(buffer == 'E' || buffer == 'e')
flag=flag+ 1;
}
return 0;
}
The problem is that you did not a deep copy of string.
while((de = readdir(d)))
{
files[i] = de->d_name; /* you just made files[i] pointing to de->d_name, instead of
* copy the content to files[i].
*/
i++;
}
So after closedir()
, the libc
will reuse the inner buffer, the content may be modified by other function of libc
, then you got a rubbish content.Replacing it with strcpy(files[i], de->d_name)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.