While I am unsure why macos uses this instead of standard C functionality, assuming what I read years ago in "Mac OS X Unleashed" is correct, it turns out I learned something new, again.
Please look at the following simple C program:
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
struct timespec ts;
ts.tv_sec = 10;
ts.tv_nsec = 0;
FILE * fp;
fp = fopen("file.txt", "a");
int f = fileno(fp);
if (fp == NULL)
{
printf("Error opening file!\n");
exit(1);
}
struct stat file_stat;
int ret;
ret = fstat (f, &file_stat);
printf("inode number is %d\n", file_stat.st_ino);
nanosleep(&ts, NULL);
printf("Finished sleep, writing to file.\n");
/* print some text */
const char *text = "Write this to the file";
dprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
dprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single characters */
char c = 'A';
dprintf(f, "A character: %c\n", c);
close(f);
}
Compile the program, run it in the background and quickly mv file.txt file2.txt
BEFORE the program prints "Finished sleep, writing to file." (you have 10 seconds)
Notice that file2.txt
has the output of your program although it was moved before the text was printed to the file (via file descriptor).
$ gcc myfile.c
$ ./a.out &
[1] 21416
$ inode number is 83956
$ ./mv file.txt file2.txt
$ Finished sleep, writing to file.
[1]+ Done ./a.out
$ cat file2.txt
Some text: Write this to the file
Integer: 1, float: 3.141593
A character: A
DISCLAIMER: I have not pruned the "include" list, this was quickly hacked together to prove a point.