Renaming files with rename
What you'll learn: How to use the C standard library to programmatically change a file's name or move it to a new directory.
Giving a File a New Identity
In your operating system, you often right-click a file to rename it. In C, we do this using the rename function, which is found in the <stdio.h> header.
Think of a file like a physical folder in a filing cabinet. The "name" is just a label written on the tab. When you use rename, you aren't changing the contents of the folder; you are simply erasing the old label and writing a new one. If you provide a different folder path as part of the new name, it’s like picking up the folder and sliding it into a different drawer.
The Syntax
The rename function takes two strings: the current name (the source) and the new name (the destination).
#include <stdio.h>
int main() {
char old_name[] = "draft_v1.txt";
char new_name[] = "final_report.txt";
// rename returns 0 on success
if (rename(old_name, new_name) == 0) {
printf("File renamed successfully.\n");
} else {
// If the file doesn't exist or permissions are denied
perror("Error renaming file");
}
return 0;
}
How It Behaves
There are a few important rules to keep in mind when using this function:
- Success and Failure: The function returns
0if it works. If it fails (for example, if the original file doesn't exist), it returns a non-zero value. - Overwriting: If a file with the "new name" already exists, the behavior depends on your operating system. Usually,
renamewill silently delete the existing file and replace it with your renamed one. It is like putting a new folder exactly where an old one was—the old one gets tossed out. - Moving Files: You can use
renameto move a file across directories on the same disk drive (e.g., fromdata/old.txttoarchive/old.txt). However, it generally won't work if you try to move a file from one physical drive to another (like from a hard drive to a USB stick).
Key takeaway
Use rename("old.txt", "new.txt") to change a file's name or location, always checking the return value to ensure the operation succeeded.