Compress Spaces in a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Compress Multiple Consecutive Spaces in a Text File into a Single Space

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.

C program to compress multiple consecutive spaces in a text file into a single space using fgetc, a state flag, and fputc, with step-by-step explanation.

📝 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:

  1. Ask for the source filename.
  2. Open the source in read mode ("r") and a temporary file in write mode ("w").
  3. Set the flag prev_space = 0 to mean "the previous byte was not a space."
  4. Read one byte at a time with fgetc().
  5. For each byte: if it's a space and prev_space is already 1, skip it. Otherwise, write it and update prev_space accordingly.
  6. Close both files, then remove() the original and rename() 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:

Contents of messy.txt before (spaces shown as █): Hello███World
The██quick████brown████fox
████Indented██text

Running the program:

Console: Enter the filename: messy.txt
Done. Read 62 bytes, wrote 47, removed 15 duplicate space(s).

After the program finishes, messy.txt contains:

Contents of messy.txt after (spaces shown as █): Hello█World
The█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.
⚠️ Important: This program only compresses the space character (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 fclose before remove/rename: On Windows, remove and rename fail if either file is still open.
  • Resetting prev_space at 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 negative char value is undefined behavior. Cast to unsigned 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/rename return 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 example filename + ".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 -g to catch type issues.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 19. Convert a Text File to Uppercase
  • 21. Print Odd Lines Followed by Even Lines
  • 6. Delete a Specific Line from a Text File
  • 10. Replace a Word with Another Word in a Text File
  • 5. Count Characters, Words, and Lines in a Text File
  • File Handling in C — Introduction

Previous Problem: -->> 19. Convert a Text File to Uppercase   ||   Next Problem: -->> 21. Print Odd Lines Followed by Even Lines

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.