How to rename a file using C++

In this tutorial, we will learn how to rename a file using C++. Renaming the file is a very important thing if we save any file name by mistake in that time we need to rename our file name that’s why renaming is a very important thing.

Rename a file using C++

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    char oldFileName[] = "oldFile.txt";
    char newFileName[] = "newFile.txt";

    if (rename(oldFileName, newFileName) == 0) {
        cout << "File renamed successfully." <<endl;
        return 0;
    } else {
        cout<< "Error renaming file." << endl;
        return 1;
    }
}

OUTPUT:-

 

Renaming a file is a common task that programmers encounter when working with file systems. In C++ we use the “rename()” function for renaming the file name. We take the “rename()” function as form standard library function from C.

#include <cstdio>

This header file is used for the rename function.

rename(oldFileName, newFileName)

In the rename function, we need to pass the old file name first then we need to pass the new file name.

When the file name is changed successfully then the function returns 0 that’s why we check whether the file name changed or not using if else.

Leave a Comment

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

Scroll to Top