Table of Contents

IronForgeCyber

Courses

Resources

Blog

Log In



IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. c-programming
  3. file-io
8 min read

File I/O

The last lesson showed the raw descriptors underneath everything. In day-to-day C you rarely call read and write directly for files — you use the standard I/O layer: FILE *, fopen, fgets, fread, and friends. It buffers for you and comes with convenient helpers for both text and binary data. This is the toolkit you will reach for in nearly every challenge in this section, so it is worth having in one place.

Opening Files and the File Pointer

You open a file with fopen, which takes a path and a mode string and returns a FILE * — the buffered wrapper around a descriptor from the last lesson. It returns NULL if the file could not be opened, so you always check:

c
1FILE *fp = fopen("data.txt", "r");
2if (fp == NULL)
3{

The common modes are "r" to read, "w" to write (truncating any existing contents), and "a" to append. Add a b — "rb", "wb" — when the data is binary rather than text. When you are done, fclose(fp) flushes anything still buffered and releases the descriptor.

your codefgets / fprintf FILE *buffer fd → kernel→ disk the buffer turns many small calls into a few large reads and writes

Reading Text Line by Line

Most input is text, read a line at a time. fgets reads one line into a buffer you provide, and crucially it takes the buffer's size, so it will never overflow it:

c
1char line[128];
2while (fgets(line, sizeof(line), fp) != NULL)

The loop keeps going until fgets returns NULL, which happens at end of file. Here it is end to end — writing three lines, then reading them back:

lineio.c
1#include <stdio.h>
2
3int main(void)
4{
5
$ gcc lineio.c -o lineio$ ./lineioread: alpharead: bravoread: charlie

When you do not want to pick a buffer size at all, getline allocates and grows one for you — which is why the challenges in this section reach for it constantly. You hand it the address of a char * (starting as NULL) and a size_t; it reads a full line however long, updating both, and returns the number of bytes read, or -1 at end of file. The buffer it allocates is yours, so free it when the loop ends:

getline.c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void)

One catch trips up almost everyone: getline is a POSIX function, not part of ISO C (the same is true of the ssize_t type its result is often stored in). With GCC's defaults it is available, but compile in a strict standards mode like -std=c11 and it disappears — the compiler reports an implicit declaration. You expose it by setting the feature-test macro _POSIX_C_SOURCE to 200809L (POSIX-2008, the revision that standardized getline):

$ gcc -std=c11 getline.c -o getlinegetline.c:14:12: error: implicit declaration of function ‘getline’ [-Wimplicit-function-declaration]$ gcc -std=c11 -D_POSIX_C_SOURCE=200809L getline.c -o getline$ ./getlineread: alpharead: bravo

So keep -D_POSIX_C_SOURCE=200809L within reach — or put #define _POSIX_C_SOURCE 200809L as the very first line of the file, before any #include. It is covered again, in context, in the ASCII challenges introduction.

Reading Binary Data

When a file holds raw bytes rather than text — the serialized challenges — you use fread and fwrite. fread takes a destination, the size of one element, how many elements to read, and the file, and returns how many it actually read. Opening in binary mode ("rb"/"wb") keeps the system from translating bytes on you:

binio.c
1#include <stdint.h>
2#include <stdio.h>
3
4int main(void)
$ gcc binio.c -o binio$ ./biniogot 100got 200got 300

The loop condition — fread(...) == 1 — is the binary equivalent of checking for NULL: it keeps reading one element at a time until fread comes up short at the end of the file.

Parsing a Line

Reading gets you a line of text; the next job is usually pulling values out of it. You already have the tools from the strings lesson: strtok to split a line into tokens on a delimiter, strtol (or atoi) to turn a token into a number, and sscanf to pull fields straight out of a formatted line:

c
1int day, month, year;
2sscanf(line, "%d/%d/%d", &day, &month, &year);

Which one you use depends on how regular the input is — sscanf when the format is fixed, strtok when you are walking a variable list of fields.

Closing Up and EOF

Two habits round this out. Always fclose what you fopen: it flushes the buffer (so your writes actually reach disk) and frees the descriptor. And know how each reader signals end of file — fgets returns NULL, getline returns -1, and fread returns fewer elements than you asked for. Those return values are the EOF check, which is why every read loop in this section is written around them rather than testing feof up front.

That is the whole input pipeline: open a file, read it line by line or record by record, parse what you read into arrays and structs, and close up — everything the challenges rely on. Next, the Tools section covers building and debugging programs larger than a single file, starting with Compilation.

4 printf("could not open the file\n");
5 return 1;
6}
3{
4 // line includes the trailing '\n'
5}
FILE
*
fp
=
fopen
(
"data.txt"
,
"w"
)
;
6 fputs("alpha\n", fp);
7 fputs("bravo\n", fp);
8 fputs("charlie\n", fp);
9 fclose(fp);
10
11 fp = fopen("data.txt", "r");
12 char line[64];
13 while (fgets(line, sizeof(line), fp) != NULL)
14 printf("read: %s", line);
15 fclose(fp);
16 return 0;
17}
5{
6 FILE *fp = fopen("lines.txt", "w");
7 fputs("alpha\n", fp);
8 fputs("bravo\n", fp);
9 fclose(fp);
10
11 fp = fopen("lines.txt", "r");
12 char *line = NULL;
13 size_t len = 0;
14 while (getline(&line, &len, fp) != -1)
15 printf("read: %s", line);
16
17 free(line);
18 fclose(fp);
19 return 0;
20}
5{
6 uint32_t values[3] = { 100, 200, 300 };
7
8 FILE *fp = fopen("nums.bin", "wb");
9 fwrite(values, sizeof(uint32_t), 3, fp);
10 fclose(fp);
11
12 fp = fopen("nums.bin", "rb");
13 uint32_t n;
14 while (fread(&n, sizeof(n), 1, fp) == 1)
15 printf("got %u\n", n);
16 fclose(fp);
17 return 0;
18}