Created
February 7, 2023 00:33
-
-
Save gdetor/8d95377d3a3094787795d1f2fc32955c to your computer and use it in GitHub Desktop.
RAII in C (close a file)
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 <stdio.h> | |
/* #include <stdlib.h> */ | |
static inline void fclosep(FILE **fp) { if (*fp) fclose(*fp); *fp=NULL; } | |
#define _cleanup_fclose_ __attribute__((cleanup(fclosep))) | |
void example_usage(void) | |
{ | |
_cleanup_fclose_ FILE *logfile = fopen("logfile.txt", "w+"); | |
fputs("hello logfile!", logfile); | |
} | |
int main() | |
{ | |
example_usage(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment