Library Function rename() in C++

Library Function in C++ : rename()

On this page we will discuss about library function rename() which is used in C++. rename() is a function in the C++ standard library that allows you to change the name of a file. The cstdio header file is a C++ standard library header file that provides functions for performing input and output operations.

Select query in dbms

Library Function rename() in C++

In C++ programming language, the rename() function is included in cstdio header file.

The rename() function is used to change the name by passing as an argument of a file from old name to new name without changing the file’s content. If new name is the same as the name of an existing file in the same folder, then the function may override the existing file, depending on the system and library implementation.

The rename() function can also be used to move a file to a different directory. Instead of copying the file to the new location, the original file is moved to the new directory location.


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


This function takes two input parameters.

oldnameA string containing the name of the file you want to rename.
newnameA string containing the new name for the file.

Return value

The return type of rename() function is an integer.

  • This function returns zero on success i.e. if the file is renamed successfully.
  • This function returns a non-zero value on error.

Implementation of Library Function rename() in C++

Example 1:

The following code shows the use of rename function.
#include <iostream> 
#include <cstdio>
using namespace std;

int main()
	const char* oldname = "old_file.txt";
        const char* newname = "new_file.txt";
	/*	Deletes the file if exists */
	if (rename(oldname, newname) != 0)
		perror("Error renaming file");
		cout << "File renamed successfully";
	return 0;


  • If the file is renamed successfully:
File renamed successfully
  • If an error occurred:
Error renaming file: No such file or directory

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription