In this article, we will write a C program to rename a file. The program asks the user to enter the name or path of the file to be renamed and the new file name and simply rename it. If the file with the specified file name does not exist or some other error occurs, it prompts the user.
Sample Input:
Enter the old name of the file: myfile.txt Enter the new name of the file: myfile_new.txt
Sample Output:
File renamed successfully.
To rename a file in C programming language, you can use the rename() function provided by the standard I/O library(<stdio.h>
).
The rename()
function takes two arguments, the current name of the file or directory and the new name you want to assign to it.
The rename()
function returns zero if the renaming operation is successful. If an error occurs during the renaming process, it returns a non-zero value (usually -1).
int rename(const char *oldname, const char *newname);
See implementation in the following program:
// C program to rename a file #include <stdio.h> int main(){ char old_filename[100], new_filename[100]; int isRenamed; printf("Enter the old name of the file: "); scanf("%s", &old_filename); printf("Enter the new name of the file: "); scanf("%s", &new_filename); // Rename the file isRenamed = rename(old_filename, new_filename); if(isRenamed == 0){ printf("File renamed successfully."); } else{ printf("Unable to rename the file"); } return 0; }
Output:
Enter the old name of the file: myfile.txt Enter the new name of the file: myfile_new.txt File renamed successfully. Enter the old name of the file: data/myfile.txt Enter the new name of the file: data/myfile_new.txt File renamed successfully.
You can also specify the path of the file if the file is not in the same directory where your program file is located.
That’s all for this article. Thanks for reading.