The C library rename(const char *old_filename, const char *new_filename) function causes the filename referred to by old_filename to be changed to new_filename.
SyntaxFollowing is the C library syntax of the rename() function −
int rename(const char *old_filename, const char *new_filename);Parameters
This function accepts the two parameters −
The rename function returns both integer or non-integer value:
1. 0: If the operation is successful.
2. Non-zero value: If the operation fails. The exact value can vary, but in general, you can use errno to get more information about the error. Common errors include:
This example renames a file named oldfile.txt to newfile.txt.
Below is the illustration of the C library rename() function.
#include <stdio.h> int main() { if (rename("oldfile.txt", "newfile.txt") == 0) { printf("File renamed successfully.\n"); } else { perror("Error renaming file"); } return 0; }Output
The above code produces following result−
File renamed successfully.Example 2: Rename with Error Handling
This example attempts to rename a non-existent file, demonstrating error handling and usage of errno.
#include <stdio.h> #include <errno.h> int main() { if (rename("nonexistentfile.txt", "newname.txt") != 0) { perror("Error renaming file"); printf("Error code: %d\n", errno); } else { printf("File renamed successfully.\n"); } return 0; }Output
After execution of above code, we get the following result
Error renaming file: No such file or directory Error code: 2
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4