Scoped cleanup
A with-file block macro that always closes the file: RAII in one macro.
+ <stdio.h>
# Cleanup is just a macro: open, run the indented body, always close.
@m with_file($f, $path, $body:block)
for $f: *FILE = fopen($path, "r"); $f; $f = (fclose($f), (FILE *)0)
$body
f count(path: str) i32
n:=0
@with_file(f, path)
while fgetc(f) != EOF
++n
< n
f main()
printf("bytes: %d\n", count("/dev/null"))
printf("missing: %d\n", count("/no/such/file"))
< 0
#include <stdio.h>
int count(const char *path) {
int n = 0;
for (FILE *f = fopen(path, "r"); f; f = (fclose(f), (FILE *)0)) {
{
while (fgetc(f) != EOF) {
++n;
}
}
;
}
return n;
}
int main(void) {
printf("bytes: %d\n", count("/dev/null"));
printf("missing: %d\n", count("/no/such/file"));
return 0;
}
Output
bytes: 0
missing: 0
What it shows
@m, block captures