# Reading & Writing Files — C Programming

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

> fprintf/fscanf for text, fread/fwrite for raw bytes.

## Read a text file line by line

`fgets` returns `NULL` at end-of-file, which doubles as the loop condition.

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

char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
    printf("%s", line);
}
fclose(fp);
```

## fwrite / fread for raw data

Binary mode reads/writes exact byte layouts — useful for structs, not just text.

```c
struct Point { int x, y; } p = {3, 4};

FILE *fp = fopen("point.bin", "wb");
fwrite(&p, sizeof(p), 1, fp);
fclose(fp);

struct Point q;
fp = fopen("point.bin", "rb");
fread(&q, sizeof(q), 1, fp);
fclose(fp);
printf("%d,%d\n", q.x, q.y);
```

Output:

```
3,4
```

**Quiz:** What does fopen return if the file cannot be opened?

- [x] NULL
- [ ] An empty string
- [ ] It crashes the program

*Answer:* NULL. fopen returns NULL on failure -- always check before using the handle.
