CKTIS / C
rename — rename a file
The rename function from <stdio.h> changes a file's name. It returns 0 on success and a nonzero value on failure.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <stdio.h>
int rename(const char *old, const char *new);rename(old, new) takes two null-terminated strings: the file's existing and replacement names. After success, the file is no longer accessible under its old name.
If the destination already exists, behavior is implementation-defined: do not assume portable replacement. On failure, an existing source file retains its original name.
The operation can fail, for example, when the file is open or renaming requires copying its contents. The example closes the file before renaming and tests the result using != 0, not == -1.
Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Run in a private directory where no other process changes these names. */
FILE *file = fopen("rename-before.txt", "wx");
if (file == NULL) {
return EXIT_FAILURE;
}
if (fclose(file) != 0) {
return EXIT_FAILURE;
}
/* Reserve the destination without opening or truncating an existing file. */
FILE *destination = fopen("rename-after.txt", "wx");
if (destination == NULL) {
return EXIT_FAILURE;
}
if (fclose(destination) != 0) {
remove("rename-after.txt");
return EXIT_FAILURE;
}
/* Some implementations do not allow rename to replace the placeholder. */
if (rename("rename-before.txt", "rename-after.txt") != 0) {
remove("rename-after.txt");
return EXIT_FAILURE;
}
if (remove("rename-after.txt") != 0) {
return EXIT_FAILURE;
}
puts("Renamed and removed.");
return EXIT_SUCCESS;
}Result
Renamed and removed.
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.