How To Rename a File in C++?

In this tutorial, we will learn How to rename a file in C++. Rename() function is defined in stdio.h header file. It renames a file from oldname to newname. hence we can also use this function to move a file.

To  Rename a File in C++

Let’s learn this with some easy steps. If this program does not work just scroll down to get the solution with the full program. (As some iostream.h and conio.h does not work on modern IDLE)

  • Firstly we start from header file in which we used two header file(iostream,stdio,conio) iostream is used for input /output stream and stdio is for standard input/output  and conio is for console input/output.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
  • this is a main function.Int tells the compiler that function will return an integer number.
int main()
  • Now we have to create a Text Document in Bin so that it get’s Renamed .
  • After that, we are Defining a Character Array for Old name and New name and ” “ write the text document name in it.
{
  char oldname[]="raj.txt";
  char newname[]="r.txt";
  • Now the If condition.
if(rename(oldname,newname)!=0)
  • In the parenthesis, if rename of oldname and newname is not equal to zero then it will print file renamed successfully else error remaining file.
  
   cout<<"file renamed successfully";
else
   cout<<"error remaining file";

 

  • Now combine the whole part of the program in a single window.

    #include<iostream.h>
    #include<conio.h>
    #include<stdio.h>
    int main()
    {
      char oldname[]="raj.txt";
      char newname[]="r.txt";
      clrscr();
    
     if(rename(oldname,newname)!=0)
        cout<<"file renamed successfully.";
     else
        cout<<"error remaining file.";
     
     return 0;
    }

    output:

    file renamed successfully.

     

Or you can use it (If you are using any modern IDLE)

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
  char file_name[] = "this_was_my_file.txt";
  char new_file_name[] = "this_is_my_file.txt";
  
  if (rename(file_name, new_file_name) != 0)
    perror("There is an error!!!");
  else
    cout << "The operation was done successfully";
  
  return 0;
}

 

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *