Let's say I have 3 files with extension ".exe" files in the folder c:/. And I want to create 3 pointers of type char*, each of this pointer contains the file name of the .exe file. So, we have 3 pointers - 3 file names. But the output is what really confuses me (see below).
My implementation:
#include <dirent.h>
// some code here
DIR *dir;
struct dirent *ent;
char** FileName = new char* [3]; // Creating 3 pointers of type char*
count = 0; //counting the events when .exe file detected
dir = opendir("c:/");
while ((ent = readdir (dir)) != NULL) // read directory file by file until there is nothing
{
string matchName = string(ent->d_name);
if (matchName.find(".exe") != std::string::npos) // Finding files with
//.exe extension only
{
FileName[count] = ent->d_name;
cout << "count = " << count << ": " << FileName[count] << endl;
count++; // There are 3 .exe files in the folder, so the maximum
// of the count=3 (from FileName[0] to FileName[2])
}
}
closedir (dir);
// Here I'm just checking the output
cout << "count = 0: " << FileName[0] << endl;
cout << "count = 1: " << FileName[1] << endl;
cout << "count = 2: " << FileName[2] << endl;
My output:
//from inside the while-loop:
count = 0: file0.exe
count = 1: file1.exe
count = 2: file2.exe
//from when I just check the output outside the loop
count = 0: // just empty for all 3 files
count = 1:
count = 2:
Why do I have expected assignment (at least, expected) while I'm inside the while-loop, but then when I'm checking the same values of the pointers outside the loop - it's just empty? Thank you!