Skip to content

Instantly share code, notes, and snippets.

@opsJson
Last active March 19, 2022 02:23
Show Gist options
  • Select an option

  • Save opsJson/6d85767844e536d6e88e4991b81fadd2 to your computer and use it in GitHub Desktop.

Select an option

Save opsJson/6d85767844e536d6e88e4991b81fadd2 to your computer and use it in GitHub Desktop.
Call a destructor function when variable is out of scope.
#include <stdio.h>
#include <stdlib.h>
#define unique_ptr(destructor) __attribute__ ((cleanup(destructor)))
void destructor(void *ptr) {
void *aux = *(void**)ptr;
fclose(aux);
printf("file closed.\n");
}
/*///////////////////////////////////
Testing:
///////////////////////////////////*/
int main(void) {
{
unique_ptr(destructor) FILE *fp;
fp = fopen("test-file.txt", "w");
fputs("Hello, world!\n", fp);
}
//destructor is called here
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment