Skip to content

Instantly share code, notes, and snippets.

@gdetor
Created February 7, 2023 00:33
Show Gist options
  • Save gdetor/8d95377d3a3094787795d1f2fc32955c to your computer and use it in GitHub Desktop.
Save gdetor/8d95377d3a3094787795d1f2fc32955c to your computer and use it in GitHub Desktop.
RAII in C (close a file)
#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