C rename
Move an existing draft to a new name in the same directory.
A simple example
rename
- Start with A file named a.txt
- Do this Rename it to b.txt
- Result b.txt holds the original contents
Syntax
rename(draft, published)
Run these examples in C
Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonPublish a signed attendance sheet
A class representative edits a draft until the names have been checked. Once the sheet is signed, rename it in the same workspace and confirm the final name is available for publication.
#define _POSIX_C_SOURCE 200809L
#if defined(__APPLE__)
#define _DARWIN_C_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(void) {
char folder[] = "/tmp/attendance-XXXXXX";
if (!mkdtemp(folder)) return 1;
char draft[128], published[128];
snprintf(draft, sizeof draft, "%s/draft", folder);
snprintf(published, sizeof published, "%s/attendance.txt", folder);
FILE *sheet = fopen(draft, "w");
int ok = 0;
if (sheet) {
int written = fputs("signed", sheet) >= 0;
int closed = fclose(sheet) == 0;
ok = written && closed && rename(draft, published) == 0;
}
if (ok) puts(strrchr(published, '/') + 1);
unlink(draft); unlink(published); rmdir(folder);
return ok ? 0 : 1;
}
attendance.txt
After the successful rename the final entry identifies the published sheet.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Rename the draft to its final name. What text can the next shift read under that name?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Rename the draft to its final name. What text can the next shift read under that name?
What to watch for
These C examples use POSIX file APIs on macOS or Linux. Moving across storage volumes can have different failure and atomicity guarantees.