hi everyone i have a problem with this code below. when i try to read all the files in a directory i can but when i try to put them in a vector, it doesn't work, all the elements in the vector become the last element added. I'm not sure what the issue is but im sure that it has something to do with pointers and how i am adding them into the vector. Any Help Would be great. Thank You

void search_directory(char * path,vector<char*>* temp)
{

    WIN32_FIND_DATA file;
    HANDLE hFind = FindFirstFile(path , &file); 

    do 
    {
        temp->push_back(file.cFileName);

    }
    while 
        (FindNextFile(hFind, &file));
    for (int i=0; i <temp->size();i++)
    {
        cout << temp->at(i);
    }

}

Recommended Answers

All 3 Replies

What are the errors?

its not an error, its only when i try to print out the whole vector, all the elements are the last entry made ....so if i added new.txt then new123.txt then new321.txt to the vector they all become new321.txt

When you push a char* into a vector, you're not adding the actual characters to the vector, but rather a memory address that points to the characters. What's probably happening in your case is that file.cFileName (a memory address) remains the same, so you keep pushing the same value over and over again into temp. However, the actual characters pointed to by file.cFileName keeps getting changed every time you call FindNextFile().

The way you're going about this is actually dangerous, because if file.cFileName ever had to change locations, you program would instantly crash the moment you tried to access to old memory. A better way to go about this is to have the type of temp be a vector of string rather than of a vector of char*.

commented: Yes. +14
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.