user3001499
user3001499

Reputation: 811

C++: Rename all files in a directory

List of whats been achieved and what I'm stuck on to help with understanding what I am asking

What I have achieved:

Open a user specified directory, display all files within this directory.

What I haven't yet achieved:

Rename all files within this directory automatically according to a predefined name - Files are currently named as random characters, I wish to automatically rename them to "August 1", "August 2", "August 3" etc. Files have different extensions though, and I wish the extensions to remain the same.

So this is how I am opening and displaying the directory:

void DirectorySelector::OpenDirectory(void)
{
    // convert directory string to const char
    DIRECTORY = directory.c_str();

    pdir = opendir (DIRECTORY);
}

void DirectorySelector::DisplayDirectory(void)
{
    // read directory
    while (pent = readdir (pdir))
    {
        std::cout << pent->d_name << "\n";
    }
}

And this is what I am stuck on, renaming the files (files have different extensions, not sure if this will cause problems later on?)

I get the following error as soon as the program hits the while loop:

Unhandled exception at 0x009657C1 in MultipleRename.exe: 0xC0000005: Access violation reading location 0xCCCCCDE0.

void DirectoryOperator::StandardRename(void)
{   
    i = 1;

    while (pent = readdir (pdir))
    {
        oldname = pent->d_name;
        newname = "August " + i;

        OLDNAME = oldname.c_str();
        NEWNAME = newname.c_str();

        rename(OLDNAME, NEWNAME);
        i++;
    }   
}

Note: All declarations handled elsewhere and have removed validation for simplicity, if you need the code I can post it. Also I have already checked that the directory is still open in the DirectoryOperator class and I am using MSVS2012 on Windows.

Thanks in advance.

Upvotes: 1

Views: 1894

Answers (2)

OfNothing
OfNothing

Reputation: 600

There is a problem with the line:

newname = "August " + i;

"August " is a char* and i is added to the pointer before it is converted into a std::string.

So, when i==1, your string will be "ugust ", and when it is 2, it will be "gust ". Very quickly, when i > 8, you will run into undefined behavior.

Solutions:

newname = "August " + std::to_string(i); // c++11

or

#include<sstream>  
...
stringstream ss;
ss << "August " << i;
newname = ss.str();

Upvotes: 2

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"I get the following error as soon as the program hits the while loop:"

Unhandled exception at 0x009657C1 in MultipleRename.exe: 0xC0000005: Access violation reading location 0xCCCCCDE0.

Most probably pdir isn't correctly initialized when the code

while (pent = readdir (pdir))

is called. The value 0xC0000005 indicates you're trying to dereference a nullptr somewhere.

Are you sure, that

pdir = opendir (DIRECTORY);

was called in sequence as intended, and the result was valid (pdir != nullptr)?

Upvotes: 1

Related Questions