How to rename a file using a Windows API?

 

Are you able to find an API to rename a file or directory? Have you checked for it?

So how we could rename a file in Windows? Have you ever noticed MoveFile API in Windows? It can be used for the same purpose.

Here’s the code snippet. Hope this is a new information for some beginners.

BOOL RenameFile(const char* pszCurrFullPath,const char* pszNewFullPath)
{
    ASSERT(pszCurrFullPath);
    ASSERT(pszNewFullPath);
    return MoveFile(pszCurrFullPath,pszNewFullPath);
}

int main()
{
    // Renaming (Moving) a file in current directory
    if(!RenameFile(“test.txt”,”new test.txt”))
    cout<<”Failed to Rename the specified file”<<endl;

    // Renaming a file at the specified path
    if(!RenameFile(“c:\\test.txt”,”c:\\new test.txt”))
    {
        cout<<”Failed to Rename the specified file”<<endl;
    }

    // Rename directory
    if(!RenameFile(“c:\\test”,”c:\\new test”))
    cout<<”Failed to Rename the directory”<<endl;

    // Error it is not possible to move a directory from another volume using MoveFile
    if(!RenameFile(“c:\\test”,”d:\\new test”))
    cout<<”Failed to Rename the directory”<<endl;

    return 0;
}

 
  • http://krishnadevan.spaces.live.com kd

    nice one..

  • gaurav

    Thanks buddy u solve my problem… keep post there type of usefull information… once again thanks a lot

  • jojo kahanding

    The function is called “rename”

    use “rename()” in why go to all this. The stdio c library is implemented in windows and is cross portable.

  • http://sarathc.wordpress.com/2009/05/24/crt-way-of-renaming-a-file/ CRT way of renaming a file « Sharing my thoughts…

    [...] Code, CRT, MSDN, Sample, Tips, windows. No Comments 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! [...]

  • http://sarathc.wordpress.com/ Sarath

    Thanks for sharing. I’ve made new post. please do see