Hi everyone,

I have to write a function that will dig into a folder and store all the filenames into an array. I will have to use that Array later to access to each of the file. My function worked, and when i tried to output onto the screen, the result was correct. However, after the function, all the Array members had the value of the final image in the folder

Here is my code

struct FolderFile
{
    char* name;
};

FolderFile fileName[1000];
int numberFile = 0;

void listFile()
{
    
    DIR *pDIR;
    struct dirent *entry;


    char  directoryName[261];
    strcpy_s(directoryName,"ImageLibrary/");
    
    if( pDIR=opendir(directoryName) )
    {
        while(entry = readdir(pDIR))
        {
            if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
            {
                if (strcmp(entry->d_name,"Thumbs.db")!=0)
                {
                
                    char tempFile[261];
                    strcpy_s(tempFile,"ImageLibrary/");
                    strcat_s(tempFile,entry->d_name);

                    fileName[numberFile].name = tempFile;
                    
                     //This will print the output to test the result.
                     //Until now, it works well and prints out the right result    
                    cout<< fileName[numberFile].name << "\n";
                    
                    numberFile= numberFile + 1;        
                }
            
            }
            

        }

                closedir(pDIR);
    }
}

After i ran this function, i supposed each of fileName.name would be the name of the file in the folder. However, they all had the name of the final file. I don't know the reason.

Anyone can help?

Edited 6 Years Ago by hl1202: n/a

on line 32 filename is used before it has been allocated. filename is nothing more than an unallocated pointer.

Since this is a c++ program instead of C, suggest you use std::vector<std::string> to hold filenames instead of that structure you declared on line 1.

Edited 6 Years Ago by Ancient Dragon: n/a

Thanks Ancient Dragon for reply. I managed to fix my code by new struct

struct FolderFile
{
      char name[100];
};

it is not a good solution but it works.

Edited 6 Years Ago by hl1202: n/a

I ran your code with your modification but I get an error at the line fileName[numberFile].name = tempFile;
saying that expression must be an modifiable Ivalue. Please help!

This article has been dead for over six months. Start a new discussion instead.