Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer confusion - c++

Tags:

c++

pointers

I've been tasked with making a simple change to a C++ application. Unfortunately I come from a Java background, and I've hit a wall with some pointer problems.

The code in question reads in a list of files from a given directory (set using an environment variable), and does something on 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 intention is to store the environment variable once, then copy it to currentFile, then concatonate the current filename to currentFile, ready to pass into ifstream.

The problem is that

currentFile = rebuildDir;

does not reset to the environment variable, so strcat keeps on using the old filename and appending to it, so:

/home/file1
/home/file2
/home/file3

will execute as

/home/file1
/home/file1/home/file2
/home/file1/home/file2/home/file3

through the loop. I'm guessing I'm making an elementry mistake with my pointers, but I haven't been able to track it down.

Thanks for any help, and apologies for the trivial question.

PS - if there's a obviously better approach to accomplish my task, please feel free to point it out :)

like image 702
Caligari Avatar asked Dec 09 '25 20:12

Caligari


1 Answers

Current file points to the same memory as rebuilddir so you modify the string in place. You need to duplicate the string. You could do something like:

char currentFile[MAX_PATH];
snprintf(currentFile, MAX_PATH, "%s%s", rebuildDir, ent->d.name);
like image 178
Laurion Burchall Avatar answered Dec 11 '25 10:12

Laurion Burchall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!