⚙️ C programming basics · Class 10 · Lesson 18 of 18 · Free
Capstone: Simple Text Editor in C – Lines, Commands and Files
⏱ About 60 minutes · ▶ run real C here — nothing to install · no sign-in
In this lesson you will
- Design a program that reads commands and calls the right function for each
- Store, insert, edit and delete lines of text with malloc'ed strings
- Save the text to a file, load it back and split a project into .h and .c files
Before screens could show a whole page, programmers edited code one line at a time with tools like ed: type a command, the editor changes a line. In this capstone you build your own line editor in C. You will write a leave letter to the principal with it and save it to a real file.
How do you read commands in a C program?
Our editor is a loop: show a prompt, read one command line, do it, repeat. Each command starts with one letter: a (add), i (insert), e (edit), d (delete), p (print), o (open), w (write), v (view file), q (quit).
fgets reads a whole line, spaces and all, which scanf("%s") cannot. It also keeps the Enter key as '\n' at the end, so we cut it off with strcspn (it finds the position of the first '\n').
This first version only shows what it understood. Try it: add a command line like "x hello" to the inputs.
> a Dear Principal, command 'a', text "Dear Principal," > d 3 command 'd', text "3" > p command 'p', text "" > q Bye!
💡 fgets returns NULL when there is no more input, so the loop also ends safely without q.
How do you store lines of text in C?
Each line can be a different length. So we keep an array of char pointers, and give each line its own malloc'ed copy (Lesson 7), exactly as long as it needs.
Why copy? fgets reuses the same `line` array for every command. If we stored a pointer to it, every stored line would change when the next command is read.
Before the program ends, free every line. Try it: add a fourth line with "a" and print again.
> a Dear Principal, > a I was absent on Monday > a as I had fever. > p 1 | Dear Principal, 2 | I was absent on Monday 3 | as I had fever. > q
How do you insert, edit and delete a line in C?
Insert at line n: move every pointer from n onwards one place down, then put the new line in the gap. Only pointers move, never the text itself, so it is fast.
Delete line n: free its text, then move the pointers after it one place up. Edit: free the old text and store a copy of the new text.
Users count lines from 1, but arrays count from 0, so line n is lines[n - 1]. Every function checks that n is a real line number. The program tries to delete line 9, which does not exist, and the check refuses. Try it: insert "Respected Madam," at line 1 and run again.
delete 9: no such line 1 | Dear Principal, 2 | I was absent on Monday. 3 | Thank you.
💡 Edit is the same idea in one step: free(lines[n - 1]); lines[n - 1] = copy_text(text);
How do you save and load a text file in C?
Save (Lesson 5): open the file with "w", write each line followed by '\n', and close it. "w" empties the file first, so the file holds exactly what is in the editor.
Load: open with "r", read each line with fgets, cut the '\n' and store a copy. A missing file gives NULL, so check it.
To prove the file really changed, show_file prints the file straight from the disk, character by character. Try it: append another item before saving.
rice - 5 kg toor dal - 2 kg sugar - 1 kg
Loaded 3 lines --- shopping.txt now --- rice - 5 kg toor dal - 2 kg sugar - 1 kg oil - 1 litre
How do you build the complete text editor in C?
Now we put it all together. Bigger C programs are split into files. buffer.h lists the functions (the "menu"), buffer.c has their code, and main.c only reads commands. main.c includes "buffer.h" so it knows the functions exist.
`static` in buffer.c hides lines and count from other files. Only buffer.c can change them, so no other code can break the buffer by mistake.
Commands: a TEXT, i N TEXT, e N TEXT, d N, p, o FILE, w FILE, v FILE, q. This run opens a draft, fixes it, writes leave.txt and then views the saved file from disk. Try it: add your own commands to the inputs, or add a new command letter to the switch.
/* buffer.h - the lines of text the editor is working on */ #ifndef BUFFER_H #define BUFFER_H #define MAX_LINES 100 #define MAX_LEN 200 int buf_count(void); int buf_insert(int n, const char *text); /* n = 1 .. count + 1 */ int buf_replace(int n, const char *text); int buf_delete(int n); void buf_print(void); int buf_save(const char *name); int buf_load(const char *name); int show_file(const char *name); /* print a file from disk */ void buf_free(void); #endif
/* buffer.c - every line is a malloc'ed string (Lesson 7) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "buffer.h"
static char *lines[MAX_LINES];
static int count = 0;
static char *copy_text(const char *s) {
char *p = malloc(strlen(s) + 1);
if (p == NULL) exit(1);
strcpy(p, s);
return p;
}
int buf_count(void) { return count; }
int buf_insert(int n, const char *text) {
if (count == MAX_LINES || n < 1 || n > count + 1) return 0;
for (int i = count; i >= n; i--) lines[i] = lines[i - 1];
lines[n - 1] = copy_text(text);
count++;
return 1;
}
int buf_replace(int n, const char *text) {
if (n < 1 || n > count) return 0;
free(lines[n - 1]);
lines[n - 1] = copy_text(text);
return 1;
}
int buf_delete(int n) {
if (n < 1 || n > count) return 0;
free(lines[n - 1]);
for (int i = n - 1; i < count - 1; i++) lines[i] = lines[i + 1];
count--;
return 1;
}
void buf_print(void) {
if (count == 0) printf("(empty)\n");
for (int i = 0; i < count; i++) printf("%3d | %s\n", i + 1, lines[i]);
}
int buf_save(const char *name) {
FILE *f = fopen(name, "w");
if (f == NULL) return 0;
for (int i = 0; i < count; i++) fprintf(f, "%s\n", lines[i]);
fclose(f);
return 1;
}
void buf_free(void) {
for (int i = 0; i < count; i++) free(lines[i]);
count = 0;
}
int buf_load(const char *name) {
FILE *f = fopen(name, "r");
if (f == NULL) return 0;
buf_free();
char buf[MAX_LEN];
while (count < MAX_LINES && fgets(buf, sizeof buf, f) != NULL) {
buf[strcspn(buf, "\n")] = '\0';
lines[count++] = copy_text(buf);
}
fclose(f);
return 1;
}
int show_file(const char *name) {
FILE *f = fopen(name, "r");
if (f == NULL) return 0;
printf("----- %s -----\n", name);
int c;
while ((c = fgetc(f)) != EOF) putchar(c);
printf("----- end -----\n");
fclose(f);
return 1;
}
Dear Sir, I was absent on Monday because of a cricket match. Yours,
Mini editor. Commands: a i e d p o w v q > o draft.txt 4 lines read from draft.txt > p 1 | Dear Sir, 2 | I was absent on Monday 3 | because of a cricket match. 4 | Yours, > e 1 Respected Principal, > e 3 because I had fever. > i 3 and Tuesday > a Riya, Class 10 B > p 1 | Respected Principal, 2 | I was absent on Monday 3 | and Tuesday 4 | because I had fever. 5 | Yours, 6 | Riya, Class 10 B > d 9 ? could not do that > w leave.txt 6 lines written to leave.txt > v leave.txt ----- leave.txt ----- Respected Principal, I was absent on Monday and Tuesday because I had fever. Yours, Riya, Class 10 B ----- end ----- > q Bye!
💡 sscanf(arg, "%d %n", &n, &pos) reads the line number and stores in pos where the text after it starts.
🤔 Predict the output
Think like C: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
char s[] = "hello\n";
s[strcspn(s, "\n")] = '\0';
printf("[%s] %zu\n", s, strlen(s));Question 2. What does this print?
const char *arg = "2 Good morning";
int n = 0, pos = 0;
sscanf(arg, "%d %n", &n, &pos);
printf("%d|%s\n", n, arg + pos);Question 3. This deletes line 2 (counting from 1). What does it print?
const char *lines[] = { "A", "B", "C", "D" };
int count = 4, del = 2;
for (int i = del - 1; i < count - 1; i++) lines[i] = lines[i + 1];
count--;
for (int i = 0; i < count; i++) printf("%s ", lines[i]);
printf("\n");🧩 Your challenge
Add two new commands to a smaller editor: `f WORD` prints every line that contains WORD (with its line number), or "not found"; `n` prints the number of lines and characters. Use strstr from <string.h>: it returns NULL when the word is not in the line. Example for the inputs given: 2 | I was absent on Monday 3 | and on Monday evening too. not found Lines: 3, characters: 63
> a Dear Principal, > a I was absent on Monday > a and on Monday evening too. > f Monday 2 | I was absent on Monday 3 | and on Monday evening too. > f Sunday not found > n Lines: 3, characters: 63 > q
⚠️ Common mistakes (and how to fix them)
❌ Wrong
char buf[20];
const char *lines[2];
strcpy(buf, "first line");
lines[0] = buf;
strcpy(buf, "second line");
lines[1] = buf;
printf("%s / %s\n", lines[0], lines[1]);Compiles and runs, but prints: second line / second line ⏎
✅ Right
char buf[20];
char *lines[2];
strcpy(buf, "first line");
lines[0] = malloc(strlen(buf) + 1);
strcpy(lines[0], buf);
strcpy(buf, "second line");
lines[1] = malloc(strlen(buf) + 1);
strcpy(lines[1], buf);
printf("%s / %s\n", lines[0], lines[1]);
free(lines[0]);
free(lines[1]);Both pointers point at the same buf, so both lines show whatever was read last. Store a malloc'ed copy of each line.
❌ Wrong
char cmd[] = "q\n"; /* what fgets gives you */
if (strcmp(cmd, "q") == 0) printf("quit\n");
else printf("unknown command\n");Compiles and runs, but prints: unknown command ⏎
✅ Right
char cmd[] = "q\n"; /* what fgets gives you */
cmd[strcspn(cmd, "\n")] = '\0';
if (strcmp(cmd, "q") == 0) printf("quit\n");
else printf("unknown command\n");fgets keeps the '\n' from the Enter key, so the string is "q\n", not "q". Cut the newline right after every fgets.
❌ Wrong
FILE *f = fopen("notes.txt", "w");
if (f) { fprintf(f, "Buy notebooks\n"); fclose(f); }
f = fopen("notes.txt", "w"); /* meant to READ it */
char line[50] = "(nothing read)";
if (f) { if (fgets(line, sizeof line, f) == NULL) strcpy(line, "(empty)"); fclose(f); }
printf("%s\n", line);Compiles and runs, but prints: (empty) ⏎
✅ Right
FILE *f = fopen("notes.txt", "w");
if (f) { fprintf(f, "Buy notebooks\n"); fclose(f); }
f = fopen("notes.txt", "r");
char line[50] = "(nothing read)";
if (f) { if (fgets(line, sizeof line, f) == NULL) strcpy(line, "(empty)"); fclose(f); }
printf("%s", line);Opening with "w" empties the file at once, so the saved text is lost. Open with "r" to read; use "w" only when you are about to write the whole file.
📌 Remember
- A command loop reads a line with fgets, cuts the '\n', and picks an action by its first letter.
- Keep text as an array of char pointers, each pointing to its own malloc'ed copy.
- Insert and delete by moving pointers; always check that the line number is real.
- Save with "w" and fprintf, load with "r" and fgets, and free all lines at the end.
- Split a bigger program into a .h file (the list of functions) and .c files (the code).
Finished the quiz and the challenge?
Questions students ask
How do I make a text editor in C?
Start with a buffer: an array of strings, one per line. Add functions to insert, delete, replace and print lines, and to save and load a file. Then write a loop that reads commands and calls those functions, as in this lesson.
Why use fgets instead of scanf to read text?
scanf("%s") stops at the first space, so "Dear Principal" would be read as two words. fgets reads the whole line and never writes past the size you give it. Just remember to remove the '\n' it keeps.
What is a header file in C?
A .h file lists the functions, types and constants that other files may use. A .c file that includes it can call those functions, and the compiler joins all the .c files into one program.
How can I extend this editor?
Add undo with a stack of old versions (Lesson 14), a replace-word command with strstr, line numbers in the saved file as an option, or command-line arguments (Lesson 12) to open a file at start.