1

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!

chetmik
  • 13
  • 3

2 Answers2

2

This is a problem:

FileName[count] = ent->d_name;

Each call to readdir probably returns the same ent, just that there are different values now where it is pointing. You should copy the string out of that, instead of pointing into this temporary storage area.

The simplest way to do this is to change FileName to:

std::string FileName[3];

although it would be not much more effort to use std::vector<std::string> FileName; correctly, then you don't have your limitation of 3 files.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

Maybe your data is overwritten? Quote from readdir help: The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream. So, you should copy char array instead of assigning raw char pointers

VladimirM
  • 817
  • 5
  • 7