Pointer Confusion - C ++

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 - , :)

+3
3

, rebuilddir, . . - :

char currentFile[MAX_PATH];
snprintf(currentFile, MAX_PATH, "%s%s", rebuildDir, ent->d.name);
+5

"... reset ". "reset" -? currentFile , rebuildDir. pointee strcat, .. ( ) .

. , , , .

, std::string

const char *rebuildDir = getenv("REBUILD_DIR");
...
std::string currentFile = rebuildDir;
currentFile += ent->d_name;
ifstream raw(currentFile.c_str());
+3
int main(int argc, char *argv[])
{
    char* pDir = getenv("REBUILD_DIR");

    if (! pDir)
    {
        cerr << "did not find ENV var\n";
        exit(1);
    }

    string rebuildDir(pDir);

    DIR* asciiDir;

    if ((asciiDir = opendir(rebuildDir.c_str())) != NULL)
    {
        std::cout << "rebuild sensor, rebuild dir is " << rebuildDir << std::endl;

        struct dirent *ent;

        while ((ent = readdir(asciiDir)) != NULL)
        {
            string currentFile(rebuildDir);

            currentFile += '/' + string(ent->d_name);

            //probably want to skip "." and ".." entries...

            /*
            ifstream raw(currentFile);

            while(raw)
            {
                ...snip...
            }

            raw.close();
            */
        }

        closedir(asciiDir);
    }
    else
    {
        cerr << "coult not open dir\n";
        exit(1);
    }

    return 0;
}
+1
source

All Articles