Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #define osErrorFatal(userMsg) osErrorFatalImpl((userMsg), __FILE__, __func__, __LINE__)
- #define osAssert(expr, userMsg) \
- do { \
- if (!(expr)) \
- osErrorFatal(userMsg); \
- } while(0)
- void osErrorFatalImpl(const char *userMsg, const char *fileName,
- const char *functionName, const int lineNum);
- static const char *os_Usage = "Usage: ./stdio_buffering path/to/reg/file";
- int main(int argc, char **argv) {
- osAssert(2 == argc, os_Usage);
- /**
- * Magic mesage can be controlled with setvbuf calls:
- * 1) setvbuf(stdout, NULL, _IONBF, 0); -> magic message goes to stdout [no buffering is default for stderr]
- * 2) setvbuf(stdout, NULL, _IOLBF, 0); -> magic message goes to file [line buffering is default for stdout]
- * 3) setvbuf(stdout, NULL, _IOFBF, 0); -> magic message goes to file [full buffering is default for reg. files]
- * Also, if you append new line to prinf call magic message will go to file only in case 3).
- * */
- /**
- * This message is not printed on stdout cause of line buffering,
- * it is stored in printf's private buffer
- * */
- const char *magicMessage = "Magic happens to this message!";
- printf("%s", magicMessage);
- /**
- * Open file and redirect stdout to file
- * */
- int fd = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0644);
- osAssert(-1 != fd, "Opening file failed");
- /**
- * Save a stdout fd
- * */
- int fdCpy = dup(STDOUT_FILENO);
- osAssert(-1 != fdCpy, "Copying stdout fd failed");
- /**
- * Redirect stdout to file
- * */
- osAssert(dup2(fd, STDOUT_FILENO), "Redirecting stdout to file failed");
- printf("\nThis message will go to file along with magic message!\n");
- fflush(NULL); // assure that all streams are flushed
- /**
- * Restore stdout fd
- * */
- osAssert(-1 != dup2(fdCpy, STDOUT_FILENO), "Restoring stdout failed");
- /**
- * This goes to stdout
- * */
- printf("Finally stdout!\n");
- return 0;
- }
- void osErrorFatalImpl(const char *userMsg, const char *fileName,
- const char *functionName, const int lineNum) {
- perror(userMsg);
- fprintf(stderr, "File: '%s'\nFunction: '%s'\nLine: '%d'\n", fileName, functionName, lineNum);
- exit(EXIT_FAILURE);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement