CRT way of renaming a file

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.


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

–Updated–
2009/05/25 – Made the sample source compatible with both UNICODE and non-UNICODE character set.
2009/05/25 – Updated few typos

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

blog comments powered by Disqus