Rename Windows folders in C++

安稳与你 提交于 2019-12-13 00:14:59

问题


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"

回答1:


You need to use MoveFile().

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




回答2:


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

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



回答3:


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.




回答4:


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);


来源:https://stackoverflow.com/questions/22151460/rename-windows-folders-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!