rename function in C/C++

rename() function is used to change the name of the file or directory i.e. from old_name to new_name without changing the content present in the file. This function takes name of the file as its argument.
If new_name is the name of an existing file in the same folder then the function may either fail or override the existing file, depending on the specific system and library implementation.

int rename (const char *old_name, const char *new_name);

old_name : Name of an existing file to be renamed.
new_name : String containing new name of the file.

Return type of function is an integer. If the file is renamed successfully, zero is returned. On failure, a nonzero value is returned.

Assume that we have a text file having name geeks.txt, having some content. So, we are going to rename this file, using the below C program present in the same folder where this file is present.

// C program to demonstrate use of rename()
int main()
    // Old file name
    char old_name[] = "geeks.txt";
    // Any string
    char new_name[] = "geeksforgeeks.txt";
    int value;
    // File name is changed here
    value = rename(old_name, new_name);
    // Print the result
        printf("%s", "File name changed successfully");
    return 0;


If file name changed
File name changed successfully
If file name not changed
Error: No such file or directory

This article is attributed to GeeksforGeeks.org

leave a comment



load comments

Subscribe to Our Newsletter