What is rename in C?
The rename function is part of the <stdio.h> header file in C. It is used to change the name of an existing file to a new one.
The function takes in two parameters:
- old filename
- new filename
It returns an int which is 0 in case of success and a non-zero number in case of an error.
The illustration below shows how rename works:
Declaration
The rename function is defined as follows:
int rename (const char *oldName, const char *newName);
It takes in two parameters. The first is the character pointer to the old name, and the second is the character pointer to the new name.
Pointer to
charcan be in the form of achararray.
Example
The following code snippet shows how we can use rename:
We will first create a file and name it “oldFile.txt”. Then we will rename it to “newFile.txt”.
#include<stdio.h> // Including header fileint main(){FILE *fptr; // creating a pointer to filechar oldName[] = "oldFile.txt"; // setting variable for original filenamefptr = fopen(oldName, "w"); // creating a filechar newName[] = "newFile.txt"; // setting variable for new filenameint checkReturn; // variable to hold return valuecheckReturn = rename(oldName, newName); // renaming filesif(checkReturn == 0){printf("File name changed successfully");}else{printf("Error Occured");}return 0;}
As we can see above, the filename has been changed successfully.
Errors usually occur if a file of the specified name does not exist.
Free Resources