A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
rename changes the name or location of a file. On POSIX systems, if the destination exists, it is atomically replaced. Atomic means there is no moment where neither the old name nor the new name points to valid data. This property makes rename the standard technique for safe file updates: write to a temporary file, then rename it over the original. If the program crashes mid-write, the original is untouched.
#include <stdio.h>int main(void) {FILE *fp = fopen("draft.txt", "w");fputs("Final content.\n", fp);fclose(fp);int result = rename("draft.txt", "final.txt");if (result == 0) {printf("Renamed draft.txt -> final.txt\n");} else {perror("rename");return 1;}fp = fopen("final.txt", "r");if (fp) {char buf[64];fgets(buf, sizeof(buf), fp);printf("Content: %s", buf);fclose(fp);}return 0;}
On POSIX, rename fails if the old and new paths are on different filesystems (EXDEV error). It is not a move-across-devices operation. On Windows, rename fails if the destination file is already open. Always check the return value and handle platform-specific error codes.
The write-to-temp-then-rename pattern is used by databases, text editors, package managers, and config file writers. It is the simplest way to guarantee that a reader never sees a half-written file. Next: getenv, for reading environment variables from within C.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.