Summary: in this tutorial, you’ll learn how to use the C rename() function to rename a file.
Introduction to the C rename() function #
The rename() function is defined in the stdio.h standard library. The rename() function allows you to change the name of a file to a new one.
The following shows the syntax of the rename() function:
int rename ( const char * oldname, const char * newname );Code language: C++ (cpp)The rename() function takes two parameters:
oldnameis the name of the file that you want to rename.newnameis the new name of the file.
The rename() function returns 0 on success or -1 on failure.
Note that to delete a file, you use the remove() function.
C rename() function example #
The following program shows how to use the rename() function to rename the test.txt file in the current directory to new_test.txt file:
#include <stdio.h>
int main()
{
char *oldname = "test.txt";
char *newname = "new_test.txt";
if (rename(oldname, newname) == 0)
printf("The file %s was renamed to %s.", oldname, newname);
else
printf("Error renaming the file %s.", oldname);
return 0;
}Code language: C++ (cpp)If the tets.txt file exists, the program will show the following message:
The file test.txt was renamed to new_test.txt.Code language: C++ (cpp)In case an error occurs, for example, the file doesn’t exist or it is locked by another program, you’ll see the following message:
Error renaming the file test.txtCode language: C++ (cpp)Summary #
- Use the C
rename()function from the standard library to rename a file.