How to Rename a File in C Using rename() Function
In C, you can rename a file using the
rename() function from stdio.h. It takes two arguments: the current file name and the new file name, and returns 0 on success or a non-zero value on failure.Syntax
The rename() function changes the name of a file. It requires two parameters:
- old_filename: The current name of the file you want to rename.
- new_filename: The new name you want to give the file.
The function returns 0 if the rename is successful, or a non-zero value if it fails (for example, if the old file does not exist or the new name is invalid).
c
int rename(const char *old_filename, const char *new_filename);
Example
This example shows how to rename a file named oldfile.txt to newfile.txt. It checks if the rename was successful and prints a message accordingly.
c
#include <stdio.h> int main() { const char *old_name = "oldfile.txt"; const char *new_name = "newfile.txt"; if (rename(old_name, new_name) == 0) { printf("File renamed successfully from '%s' to '%s'.\n", old_name, new_name); } else { perror("Error renaming file"); } return 0; }
Output
File renamed successfully from 'oldfile.txt' to 'newfile.txt'.
Common Pitfalls
- Trying to rename a file that does not exist will cause
rename()to fail. - If the new file name already exists, behavior depends on the system; it may overwrite or fail.
- Not checking the return value of
rename()can hide errors. - Using relative or absolute paths incorrectly can cause the function to fail.
Always check the return value and use perror() to get error details.
c
#include <stdio.h> int main() { // Wrong: Not checking return value rename("nonexistent.txt", "newname.txt"); // Right: Check return value and handle error if (rename("nonexistent.txt", "newname.txt") != 0) { perror("Failed to rename file"); } return 0; }
Output
Failed to rename file: No such file or directory
Quick Reference
Remember these tips when renaming files in C:
- Include
stdio.hto userename(). - Pass correct old and new file names as strings.
- Check the return value to confirm success.
- Use
perror()to print error messages.
Key Takeaways
Use the standard
rename() function from stdio.h to rename files in C.Always check the return value of
rename() to handle errors properly.Provide valid existing old file name and desired new file name as arguments.
Use
perror() to get clear error messages when renaming fails.Be careful with file paths and existing files to avoid unexpected behavior.