The <cstdio>
oldname
(character) and newname
(character), and returns an integer value.
The rename()
function is used to change the name of a file or directory from oldname
to newname
without the contents of the file or directory itself being altered in the process. If the new name is already associated with an existing file, then that file is overwritten or the
The rename()
function can also be used to transfer a file to a new directory location. The file is not copied to the new location, instead, the original file is moved to the new directory location.
int rename(const char *oldname,const char *newname)
*oldname
*newname
Both parameters need to be of the same type, i.e., they either need to both be files or they both need to be directories.
If the file is successfully renamed, the function returns a value of -1. If it is unsuccessful, the function returns zero.
The code example below shows a case where the rename()
function successfully executes, and a case where it fails.
#include <iostream>#include <cstdio>using namespace std;int main(){//In this case an existent file is successfully renamed.char oldname1[] = "oldfile.txt";char newname[] = "newfile.txt";if (rename(oldname1, newname) != 0)cout << "There was an error renaming the file." << endl;elsecout << "File renamed successfully!" << endl;//In this case the file being renamed is non-existent hence, the renaming is unsuccessful.char oldname2[] = "errorfile.txt";if (rename(oldname2, newname) != 0)cout << "There was an error renaming the file." << endl;elsecout << "File renamed successfully!" << endl;return 0;}