Read the old and new filenames and then rename the given file using rename() function.
The rename() function is a library function of <stdio.h> header file which is used to change the name of the file or directory without changing its content.
Syntax:
int rename (const char *old_name, const char *new_name);
The argument old_name is the current name of the file or directory and the new_name is the new name of the file or directory.
The return type of the rename() function is an integer. If the file or directory is renamed successfully, the function returns 0, nonzero on failure.
Program:
The source code to rename a file using rename() 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 rename() function
#include <stdio.h>
int main()
{
char oldName[16];
char newName[16];
int ret = 0;
printf("Enter old filename: ");
scanf("%s", oldName);
printf("Enter new filename: ");
scanf("%s", newName);
ret = rename(oldName, newName);
if (ret == 0)
printf("File renamed successfully\n");
else
printf("Unable to rename file\n");
return 0;
}
Output:
Enter old filename: file.txt
Enter new filename: newfile.txt
File renamed successfully
Explanation:
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 rename() function and printed the appropriate message on the console screen.
Read the old and new filenames and then rename the given file using rename() function.
The rename() function is a library function of <stdio.h> header file which is used to change the name of the file or directory without changing its content.
Syntax:
The argument old_name is the current name of the file or directory and the new_name is the new name of the file or directory.
The return type of the rename() function is an integer. If the file or directory is renamed successfully, the function returns 0, nonzero on failure.
Program:
The source code to rename a file using rename() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
Output:
Explanation:
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 rename() function and printed the appropriate message on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer