# Managing file reading, closing + buffer allocation and deallocation

**URL:** <https://ziggit.dev/t/managing-file-reading-closing-buffer-allocation-and-deallocation/2389>\
**Category:** Help\
**Tags:** memory-management\
**Created:** [December 6, 2023, 3:53pm UTC](https://ziggit.dev/t/managing-file-reading-closing-buffer-allocation-and-deallocation/2389 "2023-12-06T15:53:17Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![gonzo](https://ziggit.dev/user_avatar/ziggit.dev/gonzo/32/54_2.png) [@gonzo](https://ziggit.dev/u/gonzo)\
**Post date:** [December 6, 2023, 6:20pm UTC](https://ziggit.dev/t/managing-file-reading-closing-buffer-allocation-and-deallocation/2389/10 "2023-12-06T18:20:15Z")

</div>

Because you want to close the file in two separate contexts (once you are done and when there was an error), you could also declare it as `var file: ?File` and, when closing, check if it is valid:

```zig
errdefer { if (file) |f| { f.close(); f = null; }
// do stuff
...
// eagerly close the file:
if (file) |f| { f.close(); f = null; }
// do more stuff, file is now closed
...

```

---

_[View the full topic](https://ziggit.dev/t/managing-file-reading-closing-buffer-allocation-and-deallocation/2389)._
