Skip to content

Instantly share code, notes, and snippets.

@int0x33
Created February 17, 2019 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int0x33/baacb88eb9760b06c1a56106ab8c031e to your computer and use it in GitHub Desktop.
Save int0x33/baacb88eb9760b06c1a56106ab8c031e to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define MY_TMP_FILE "/tmp/file.tmp"
enum { FILE_MODE = 0600 };
int main(int argc, char* argv[])
{
int fd;
FILE* f;
/* Remove possible symlinks */
unlink(MY_TMP_FILE);
/* Open, but fail if someone raced us and restored the symlink (secure version of fopen(path, "w") */
fd = open(MY_TMP_FILE, O_WRONLY|O_CREAT|O_EXCL, FILE_MODE);
if (fd == -1) {
perror("Failed to open the file");
return EXIT_FAILURE;
}
/* Get a FILE*, as they are easier and more efficient than plan file descriptors */
f = fdopen(fd, "w");
if (f == NULL) {
perror("Failed to associate file descriptor with a stream");
return EXIT_FAILURE;
}
fprintf(f, "Hello, world\n");
fclose(f);
/* fd is already closed by fclose()!!! */
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment