Read the old and new filename, and then rename the given file using the system() function by specifying the "mv" command.
The system() function is a library function of <stdlib.h> or <cstdlib> header file which is used to execute the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed.
int system(const char *string);
The argument string is the command to be executed.
To rename a file, create (form) mv command with old and new file names and pass it into the system() function.
The source code to rename a file using the system() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to rename a file
// using the system() function.
int ret = 0;
printf("Enter old filename: ");
printf("Enter new filename: ");
sprintf(cmd, "mv %s %s", oldName, newName);
ret = system(cmd);
if (ret == 0)
printf("File renamed successfully\n");
printf("Unable to rename file\n");
Enter old filename: file.txt
Enter new filename: newfile.txt
File renamed successfully
Here, we created two character arrays oldName, newName. Then we read the old and new names of files from the user. Then we renamed the given file using the system() function by specifying the "mv" command and printed the appropriate message on the console screen.
total answers (1)
start bookmarking useful questions and collections and save it into your
own study-lists, login now to start creating your own collections.