C program to rename a file using rename() function

Write a C program to rename a file using rename() function. How to rename a file using rename() function in C programming. rename() function in C programming.

Required knowledge

Basic Input Output, File handling

Rename a file using rename() function in C programming

rename() function in C

int rename(const char * oldname, const char * newname);

rename() function is defined in stdio.h header file. It renames a file or directory from oldname to newname. The rename operation is same as move, hence you can also use this function to move a file.

It accepts two parameter oldname and newname which is pointer to constant character, defining old and new name of file.

It returns zero if file renamed successfully otherwise returns a non-zero integer. During the rename operation if there already exists a file with newname then it replaces the existing file.

Program to rename a file using rename() function

/**
 * C program to rename a file using rename() function.
 */

#include <stdio.h>


int main()
{
    // Path to old and new files
    char oldName[100], newName[100];

    // Input old and new file name
    printf("Enter old file path: ");
    scanf("%s", oldName);

    printf("Enter new file path: ");
    scanf("%s", newName);


    // rename old file with new name
    if (rename(oldName, newName) == 0)
    {
        printf("File renamed successfully.\n");
    }
    else
    {
        printf("Unable to rename files. Please check files exist and you have permissions to modify files.\n");
    }

    return 0;
}

Output

Enter old file path: data\file3.txt
Enter new file path: data\file3
File renamed successfully.

Enter old file path: data\file3.txt
Enter new file path: data\file3
Unable to rename files. Please check files exist and you have permissions to modify files.

You can also use it for moving a file from old location to new location.

Output

Enter old file path: data/file3.txt
Enter new file path: file3.txt
File renamed successfully.

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>