C program to rename a file


This C program renames a given file from the old name to new name using the rename() function. Rename() is the predefined function used in c language to rename a file! gets() function is used to read the string

 C program to rename a file


Source code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void) 
{ 
      char oldname[80], newname[80]; 
      printf("File to rename:"); 
      gets(oldname);                    //Step 1
      printf("New name:"); 
      gets(newname);                  //Step 1
      if(rename(oldname, newname) == 0)   //Step 2
	 printf("Renamed %s to %s.\n", oldname, newname); 
      else 
	 perror("rename"); 
return 0; 
}


edit-code-image

Sample test cases:

1. File to rename:1.txt
New name:source
Renamed 1.txt to source.

2. File to rename:2.txt
New name:source1
Renamed 2.txt to source1.

Explanation:

Step 1: The oldname and newname for the given file are read from the user using gets() function.
Step 2: The rename() function renames the given file from old name to new name. If it is successful then program prints the output corresponding to that case otherwise it prints error returned from the perror() function.

More Content:Explore More