Created
February 17, 2019 12:43
-
-
Save int0x33/baacb88eb9760b06c1a56106ab8c031e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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