# Opening & Closing Files — C Programming

Source: https://www.geekswithgeeks.com/en/c/c-file-basics

> fopen, modes, and always checking for failure.

## FILE* is your handle

`fopen(path, mode)` returns a `FILE *` used for all further operations on that file, or `NULL` if it couldn't be opened. **Always** check for `NULL` before using it.

## Modes

`"r"` read, `"w"` write (truncates or creates), `"a"` append, `"r+"` read+write. Append a `b` for binary mode.

```c
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
    perror("fopen failed");
    return 1;
}

fprintf(fp, "Hello, file!\n");
fclose(fp);
```

## Always close

`fclose(fp)` flushes buffered writes to disk and releases the file handle. Forgetting it can lose data still sitting in the buffer.
