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.

  • 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.

     

You may also read:





Leave a Reply

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