Temporary files in C
tmpfile gives you a stream that deletes itself when it is closed.
#include <stdio.h>
int roundtrip(void) {
FILE *f = tmpfile();
if (f == NULL) {
return 0;
}
fprintf(f, "42 rust\n");
rewind(f);
int number = 0;
char word[16];
int matched = fscanf(f, "%d %15s", &number, word);
fclose(f);
return matched == 2 && number == 42;
}
How it works
- There is no name to clean up afterwards.
- It opens in binary update mode, so you can write then read.
rewindbefore reading back what you just wrote.
Keywords and builtins used here
FILENULLcharifintreturnroundtripvoid
The run, in numbers
- Lines
- 16
- Characters to type
- 260
- Tokens
- 90
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 54 seconds.
Step 4 of 4 in Writing & binary, step 8 of 12 in Files & I/O.