Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use rename() in C++

Eesha Zohair Mustafeez

What is the rename() function and what does it do?

The rename() functionwhich is defined in the C++ standard library <cstdio>, is a function that takes two arguments, 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 function failsA function fails when a file under the name of old name does not exist., depending on the system and libraries being used.

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.

Syntax

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

Parameters

*oldname

  • The pointer to the C string that contains the name of the existing file to be renamed.

*newname

  • The pointer to the C string that contains the new name for the existing file.

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.

Return value

If the file is successfully renamed, the function returns a value of -1. If it is unsuccessful, the function returns zero.

Implementation

The code example below shows a case where the rename() function successfully executes, and a case where it fails.

main.cpp
oldfile.txt
#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;
	else
		cout << "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;
	else
		cout << "File renamed successfully!" << endl;
	return 0;
}
Folder view before calling the rename() function
Folder view before calling the rename() function
Folder view after calling the rename() function
Folder view after calling the rename() function

RELATED TAGS

c++

CONTRIBUTOR

Eesha Zohair Mustafeez
RELATED COURSES

View all Courses

Keep Exploring