In one of the previous post I mentioned about How to rename a file using windows API. Many people have asked is there any other option than using MoveFile API for renaming a file. Yes! there’s an alternative you can C-Runtime function rename, _wrenameto rename a file. This code will be portable across platforms as it’s part of standard library function. You can also use _trename , which is a typedef of rename_wrename to make the call compatible with both UNICODE and Non-UNICODE character set
See the sample taken from MSDN itself for renaming a file.
[sourcecode language='cpp']
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR old_filename[] = _T(“CRT_RENAMER.OBJ”), new_filename[] = _T(“CRT_RENAMER.JBO”);
/* Attempt to rename file: */
int result = _trename( old_filename, new_filename );
if( result != 0 )
_tcprintf( _T(“Could not rename ‘%s’\n”), old_filename );
else
_tcprintf( _T(“File ‘%s’ renamed to ‘%s’\n”), old_filename, new_filename );
return 0;
}
[/sourcecode]
–Updated–
2009/05/25 – Made the sample source compatible with both UNICODE and non-UNICODE character set.
2009/05/25 – Updated few typos