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?

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.

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.

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!

use strcpy() to copy the tempFile to name. strcpy(fileName[numberFile].name,tempFile);

commented: Thanks :) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.