I was tasked with making a simple change for a C ++ application. Unfortunately, I'm coming from a Java background and I hit a wall with some problems with pointers.
This code is read in a list of files from a given directory (set using an environment variable) and does something in each file.
char * rebuildDir = getenv("REBUILD_DIR");
char * currentFile;
DIR *asciiDir;
struct dirent *ent;
asciiDir = opendir(rebuildDir);
if (asciiDir != NULL)
{
while ((ent = readdir(asciiDir)) != NULL)
{
std::cout << "rebuild sensor, rebuild dir is " << getenv("REBUILD_DIR") << std::endl;
currentFile = rebuildDir;
strcat(currentFile, ent->d_name);
ifstream raw(currentFile);
while(raw)
{
...snip...
}
raw.close();
}
closedir(asciiDir);
}
As you can see, the goal is to save the environment variable once and then copy it to currentFile and then map the current file name currentFile, ready to go into ifstream.
The problem is
currentFile = rebuildDir;
does not apply to the reset environment variable, therefore strcat continues to use the old file name and adds to it, therefore:
/home/file1
/home/file2
/home/file3
will run as
/home/file1
/home/file1/home/file2
/home/file1/home/file2/home/file3
through the loop. I assume that I am making an elementary mistake with my pointers, but I was not able to track it.
.
PS - , :)