Question

I was wondering if there was a simple way of programming in C++ the renaming of a Windows folder.

The program I would like to make would be something like this:

rename folder "Something A" to "Something TEMP"
rename folder "Something B" to "Something A"
rename folder "Something TEMP" to "Something B"
Was it helpful?

Solution

You need to use MoveFile().

I know it sounds funny but it works for directories too. :)

OTHER TIPS

For the operation of renaming once, see MoveFile or MoveFileEx on MSDN:

BOOL WINAPI MoveFile(
  _In_  LPCTSTR lpExistingFileName,
  _In_  LPCTSTR lpNewFileName
);

Unless your folders have names with international characters, you can in practice use the C standard library's ::rename function, from the <stdio.h> header, e.g. as follows:

#include <stdio.h>      // ::rename
#include <stdlib.h>     // ::exit, EXIT_FAILURE

auto fail( char const* const message )
    -> bool
{
    fprintf( stderr, "!%s\n", message );
    exit( EXIT_FAILURE );
}

auto main()
    -> int
{
    rename( "a", "temp" )
        == 0
        || fail( "Renaming a failed." );
    rename( "b", "a" )
        == 0
        || fail( "Renaming b failed." );
    rename( "temp", "b" )
        == 0
        || fail( "Renaming temp failed." );
}

This works also with other OS-es.

Limitations / potential problems:

  • The C standard does not explicitly state that rename also works for folders. I guess that's because C originated with Unix, and in Unix a folder is a file. In Windows the file nature of a folder is hidden with the ordinary means of access.

  • There is no wide character variant of rename, so in Windows it can't in general handle folders with international characters, unless you use Windows API functions to first obtain pure ASCII "short names" – in which case why use rename at all.

  • Modern Windows programs are usually wide-character oriented, which means a conversion down to ANSI character encoding, which is inconvenient.

Probably none of these issues are present for your use case, but if any of them are, then just use the MoveFile API function, as already mentioned in other answers.

Alternatively, if you use boost, you can use:

std::string name("old_dir");
std::string new_name("new_dir");
system::error_code ec = boost::filesystem::rename(name, new_name);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top