I am using PC AMD Athlon, WinXP Home SP2, and mingw32: g++ (GCC) 3.4.2 (mingw-special).
Problem:
*My program traverses a directory ("./BB"; could also be ".", does not matter) and reads the files in the directory, using tools from <dirent.h>
*During traversing, the files are printed to screen and read into an array (Allfiles[])
*However, when iterating through the array from 0 to the last entry, only the last entry is present, not the previous ones. How come?
#include <iostream>
#include <errno.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
constint directorySize = 20; // there are less than 20 files in "./BB"
char *AllFiles[directorySize];
int main()
{
int Index = 0;
DIR *pdir;
struct dirent *pent;
pdir=opendir("./BB"); // open directory
if (!pdir)
{
printf ("opendir() failure; terminating");
exit(1);
}
errno=0;
//read directory "./BB" and put entries into AllFiles[i]
Index = 0;
std::cout << " --- traversing directory ---: " << std::endl;
while ((pent=readdir(pdir)))
{
AllFiles[Index] = pent->d_name;
// test to show that filenames are in AllFiles[]
// a) test if present entry is in array; this works fine
std::cout << " Array " << Index << ": " << AllFiles[Index] << std::endl;
// b) test if previous entries are still in array; no they are not!
std::cout << " Reading array entries from 0 to " << Index << ": " << std::endl;
for (int j = 0; j <= Index; j++)
{
std::cout << " > j: " << j << " Array " << j << ": " << AllFiles[j];
std::cout << std::endl;
}
Index = Index + 1;
}
std::cout << std::endl;
// irrelevant code omitted
{
K i got it now, same reason as just before, but it works now
1 2 3 4 5 6 7 8 9 10
// try changing
char *AllFiles[directorySize];
// to this
std::string AllFiles[directorySize];
// or a 2 dimensional array if you want to keep it characters
// if you do change it to the string, then u have to change:
AllFiles[Index] = pent->d_name;
//to this:
AllFiles[Index] = std::string(pent->d_name);