Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is rename in C?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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:

  1. old filename
  2. 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:

How does rename work?

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 char can be in the form of a char array.

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 file
int main(){
FILE *fptr; // creating a pointer to file
char oldName[] = "oldFile.txt"; // setting variable for original filename
fptr = fopen(oldName, "w"); // creating a file
char newName[] = "newFile.txt"; // setting variable for new filename
int checkReturn; // variable to hold return value
checkReturn = rename(oldName, newName); // renaming files
if(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.

RELATED TAGS

c

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring