C++ rename()

The rename() function in C++ renames a specified file.

rename() Prototype

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

The rename() function takes a two arguments: oldname, newname and returns an integer value. It renames the file represented by the string pointed to by oldname to the string pointed to by newname.

It is defined in <cstdio> header file.

rename() Parameters

  • oldname: Pointer to the string containing the old name of the file along with the path to rename.
  • newname: Pointer to the string containing the new name of the file along with the path.

rename() Return value

The rename() function returns:

  • Zero if the file is successfully renamed.
  • Non zero if error occurs.

Example 1: How rename() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
	char oldname[] = "file_old.txt";
	char newname[] = "file_new.txt";
	
	/*	Deletes the file if exists */
	if (rename(oldname, newname) != 0)
		perror("Error renaming file");
	else
		cout << "File renamed successfully";
	
	return 0;
}

When you run the program, the output will be:

  • If the file is renamed successfully:
    File renamed successfully
  • If the file is not present:
    Error renaming file: No such file or directory

The rename() function can also be used to move a file to a different location. This can be done by providing a different path for new name of the file.

Example 2: rename() function to move a file

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
	char oldname[] = "C:\\Users\\file_old.txt";
	char newname[] = "C:\\Users\\New Folder\\file_new.txt";
	
	/*	Deletes the file if exists */
	if (rename(oldname, newname) != 0)
		perror("Error moving file");
	else
		cout << "File moved successfully";
	
	return 0;
}

When you run the program, the output will be:

  • If the file is moved successfully:
    File moved successfully
  • If the file is not present:
    Error moving file: No such file or directory