RENAME()
this function is used to rename a file or directory in the filesystem.
int rename(const char *old_filename, const char *new_filename);
* old_filename: The current name/path of the file or directory
* new_filename: The new name/path you want to assign
* Return value:
- 0 on success
- Non-zero (usually -1) on failure (errno is set)
* Changes the name of a file or directory from old_filename to new_filename
* Can also move the file to a different directory (if on the same filesystem)
* Overwrites new_filename only on POSIX systems if the file
exists (not allowed by default on Windows)
* Error examples:
- ENOENT — old_filename does not exist
- EACCES — Permission denied
- EXDEV — Moving across filesystems is not allowed
* POSIX
- Overwrites new_filename if it exists (if permitted)
Windows
- Fails if new_filename already exists
#include <stdio.h>
int main() {
if (rename("oldname.txt", "newname.txt") == 0) {
printf("File renamed successfully.\n");
} else {
perror("Error renaming file");
}
return 0;
}
Last updated