In this tutorial, you'll learn how to compress multiple consecutive spaces in a text file into a single space using the C programming language. This is a common text-normalization step — you might use it to clean up user input, tidy a file copied from a spreadsheet, or prepare text for printing. The program reads the file one byte at a time, keeps track of whether the previous byte was a space, and skips writing duplicate spaces. The output is written to a temporary file, which is then swapped in for the original.
📝 Problem Statement
Write a program in C to compress multiple consecutive spaces in a text file into a single space.
⚙️ How the Program Works
The program uses a simple "was the previous character a space?" flag. If the current byte is also a space, it's skipped — anything else is written unchanged:
- Ask for the source filename.
- Open the source in read mode (
"r") and a temporary file in write mode ("w"). - Set the flag
prev_space = 0to mean "the previous byte was not a space." - Read one byte at a time with
fgetc(). - For each byte: if it's a space and
prev_spaceis already 1, skip it. Otherwise, write it and updateprev_spaceaccordingly. - Close both files, then
remove()the original andrename()the temporary file to the original name.
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *src, *tmp;
char filename[100];
int ch;
int prev_space = 0;
long bytes_in = 0, bytes_out = 0;
int removed = 0;
printf("Enter the filename: ");
scanf("%99s", filename);
src = fopen(filename, "r");
if (src == NULL)
{
printf("Error: Could not open '%s'.\n", filename);
return 1;
}
tmp = fopen("temp.txt", "w");
if (tmp == NULL)
{
printf("Error: Could not create temporary file.\n");
fclose(src);
return 1;
}
/* Read one byte at a time and write it only if
it's not a duplicate space */
while ((ch = fgetc(src)) != EOF)
{
bytes_in++;
if (ch == ' ' && prev_space)
{
/* Skip duplicate space */
removed++;
continue;
}
fputc(ch, tmp);
bytes_out++;
prev_space = (ch == ' ');
}
fclose(src);
fclose(tmp);
if (remove(filename) != 0)
{
printf("Error: Could not replace original file.\n");
return 1;
}
if (rename("temp.txt", filename) != 0)
{
printf("Error: Could not rename temporary file.\n");
return 1;
}
printf("Done. Read %ld bytes, wrote %ld, removed %d duplicate space(s).\n",
bytes_in, bytes_out, removed);
return 0;
}🖥️ Sample Output
Assume messy.txt contains lines with irregular spacing:
messy.txt before (spaces shown as █):
Hello███WorldThe██quick████brown████fox
████Indented██text
Running the program:
Done. Read 62 bytes, wrote 47, removed 15 duplicate space(s).
After the program finishes, messy.txt contains:
messy.txt after (spaces shown as █):
Hello█WorldThe█quick█brown█fox
█Indented█text
Every run of 2+ consecutive spaces is now a single space. Notice that the leading spaces on the third line became a single leading space — the algorithm doesn't strip leading spaces, it just compresses runs.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
int prev_space = 0; |
The state flag. 0 means "the previous byte was not a space"; 1 means "it was." Initialized to 0 so leading spaces are treated as the first space of a run. |
while ((ch = fgetc(src)) != EOF) |
Reads one byte at a time. fgetc returns int so EOF is distinguishable from byte value 0xFF. |
bytes_in++; |
Counts every byte read, including the ones that will be discarded. |
if (ch == ' ' && prev_space) continue; |
The core check. If the current byte is a space and the previous byte was also a space, skip this byte — don't write it to the output. |
fputc(ch, tmp) |
Every byte that isn't a duplicate space is written unchanged — letters, digits, punctuation, newlines, tabs. |
prev_space = (ch == ' '); |
Updates the flag for the next iteration: 1 if this byte was a space, 0 otherwise. |
remove(filename); rename("temp.txt", filename); |
Replaces the original with the compressed temp file. Same pattern as Problems 6 and 10. |
0x20), not tabs or newlines. If you want to compress all whitespace (including tabs), replace ch == ' ' with isspace((unsigned char)ch) — but be careful, that would also collapse consecutive newlines, which is usually not what you want in a text file.
🧠 Why a Temporary File Is Necessary
The transformation shrinks the file — some bytes that existed in the source do not exist in the output. If you tried to write the compressed version back into the same file while still reading from it:
- Writing at an offset less than the read position would overwrite bytes you haven't read yet — losing data.
- Writing at the end (append mode) would add the compressed version after the original, producing garbage.
- The file must be truncated after the compressed data ends, which is impossible without knowing the final size in advance.
The temp-file + rename pattern sidesteps all of this: the source is never modified until the compressed copy is fully written and verified. If the program crashes mid-way, the original is untouched. This is the same pattern used by sed -i, every text editor's "save" operation, and virtually every in-place file transformation in Unix.
🔁 Common Variations
The state-flag approach generalizes to several related text-normalization tasks:
| Task | Change to the core check |
|---|---|
| Compress all whitespace (tabs too) | if (isspace((unsigned char)ch) && prev_space) continue; — and set prev_space = isspace(ch). |
| Remove ALL spaces | if (ch == ' ') continue; — no flag needed. |
| Strip leading spaces from each line | Reset a "seen non-space on this line" flag at each '\n'; skip spaces until the flag is set. |
| Strip trailing spaces from each line | Requires buffering the line (or reading backwards) — a temp-file copy won't suffice without look-ahead. |
| Compress duplicate characters (any kind) | Change prev_space to prev and compare the whole byte, not just spaces. |
🐛 Common Pitfalls
- Using the same file for source and destination: The source would be truncated before it's read. Always use a temporary file.
- Ignoring
fclosebeforeremove/rename: On Windows,removeandrenamefail if either file is still open. - Resetting
prev_spaceat the wrong point: The flag must reflect the previous byte the program saw, not just the previous byte it wrote. This code updates it for every byte read, which is correct. - Forgetting the cast when using
isspace: Passing a negativecharvalue is undefined behavior. Cast tounsigned char. - Assuming leading whitespace should be stripped: This program compresses runs of spaces but does not strip leading spaces from a line. If your requirement is "no leading spaces," you need a different algorithm.
- Not checking
remove/renamereturn values: Both return non-zero on failure. Silently ignoring them can lead to data loss — the original is gone, the temp file isn't renamed, and the user sees "Done."
💡 Tips & Best Practices
- Use a more descriptive temp file name than
"temp.txt"— for examplefilename + ".tmp"— to avoid collisions. - Print the byte reduction (as this program does) so the user can verify the operation did something.
- Open in binary mode (
"rb"/"wb") if the file contains unusual bytes, or if you want to preserve exact line endings. - Consider adding a backup copy (
filename + ".bak") before the swap, in case the user changes their mind. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch type issues.