Encrypt a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Encrypt the Contents of a Text File

In this tutorial, you'll learn how to encrypt the contents of a text file using the C programming language. The program reads the source file one byte at a time, applies a simple XOR cipher with a single-byte key, and writes the encrypted bytes to a new file. XOR encryption is the classic introduction to cryptography: it's easy to understand, easy to implement, and — most importantly — easy to decrypt. The same operation that encrypts the file will also decrypt it when you XOR with the same key.

C program to encrypt the contents of a text file using a simple XOR cipher with fgetc and fputc, with step-by-step explanation.

📝 Problem Statement

Write a program in C to encrypt the contents of a text file.

⚙️ How the Program Works

The program follows a simple read-transform-write loop:

  1. Ask for the source filename, the output filename, and the key (a single character or integer).
  2. Open the source file in binary read mode ("rb"). Binary mode is important — encrypted bytes may include values that text mode would translate or truncate.
  3. Open the destination file in binary write mode ("wb").
  4. Read the source one byte at a time with fgetc().
  5. XOR each byte with the key and write the result with fputc().
  6. Close both files when the end of the source is reached.

🔐 What Is XOR Encryption?

XOR (exclusive-or) is a bitwise operation with one extremely useful property: applying it twice with the same key undoes the first application. For any two bytes a and b:

/* XOR is its own inverse: */ (a ^ b) ^ b == a

That means the encryption function and the decryption function are the same code. If the plaintext is 'H' (0x48) and the key is 'K' (0x4B), the ciphertext is 0x03. XOR 0x03 with 0x4B again and you get 0x48 back. Here's the byte-level arithmetic for a few sample characters with key 'K':

Character ASCII (hex) Key (hex) Ciphertext (hex) Encrypted char
H 0x48 0x4B 0x03 (non-printable)
e 0x65 0x4B 0x2E .
l 0x6C 0x4B 0x27 '
o 0x6F 0x4B 0x24 $
⚠️ Important: A single-byte XOR cipher is not secure for real-world use. Its output is vulnerable to frequency analysis — an attacker who guesses common characters can recover the key in seconds. For genuine security, use AES via a library like OpenSSL. XOR is covered here because it teaches the fundamental pattern of stream ciphers, which forms the basis of more advanced algorithms.

💻 Complete C Program

#include <stdio.h> #include <stdlib.h> int main(void) { FILE *src, *dst; char src_name[100]; char dst_name[100]; int key; int ch; long bytes = 0; printf("Enter the input filename: "); scanf("%99s", src_name); printf("Enter the output filename: "); scanf("%99s", dst_name); printf("Enter the key (a single character): "); scanf(" %c", &key); /* leading space skips leftover newline */ /* Open source in binary read mode */ src = fopen(src_name, "rb"); if (src == NULL) { printf("Error: Could not open '%s'.\n", src_name); return 1; } /* Open destination in binary write mode */ dst = fopen(dst_name, "wb"); if (dst == NULL) { printf("Error: Could not create '%s'.\n", dst_name); fclose(src); return 1; } /* Read one byte, XOR it, write one byte */ while ((ch = fgetc(src)) != EOF) { fputc(ch ^ key, dst); bytes++; } fclose(src); fclose(dst); printf("%ld bytes encrypted from '%s' to '%s'.\n", bytes, src_name, dst_name); return 0; }

🖥️ Sample Output

Assume plain.txt contains a short message:

Contents of plain.txt: Hello, World!

Running the program with key 'K':

Console: Enter the input filename: plain.txt
Enter the output filename: encrypted.bin
Enter the key (a single character): K
13 bytes encrypted from 'plain.txt' to 'encrypted.bin'.

The file encrypted.bin now contains 13 bytes of binary data. Open it in a text editor and you'll see mostly unprintable characters — that's expected, because the ciphertext includes control bytes like 0x03 and 0x27. View it with xxd encrypted.bin | head to inspect the raw hex.

To decrypt, run the same program again with encrypted.bin as the input, a new output filename like decrypted.txt, and the same key 'K'. You'll get the original message back. This symmetric property is the point of Assignment 13.

🔍 Line-by-Line Explanation

Line / Code Explanation
int key; The key is stored as int so the %c format specifier works, and so we can widen it later if needed. A single character is enough here.
scanf(" %c", &key) The leading space in the format string skips any leftover whitespace — without it, the newline left over from the previous scanf would be read as the key.
fopen(src_name, "rb") Binary read mode. On Windows, text mode would translate \r\n and might truncate data on Ctrl+Z.
fopen(dst_name, "wb") Binary write mode. Creates the output file or truncates it if it already exists.
while ((ch = fgetc(src)) != EOF) Reads one byte at a time. fgetc returns int so it can signal EOF distinctly from a valid byte 0xFF.
fputc(ch ^ key, dst) XORs the byte with the key and writes the result. This single line is the entire cipher.
bytes++ Counts how many bytes were processed — useful for verification and for debugging.
fclose(src); fclose(dst); Flushes buffers and releases handles. Essential on binary files, where buffered writes may not have hit disk yet.

📂 Why Binary Mode Is Essential

Encrypting a text file produces binary output — bytes that aren't valid printable characters. If you open the output with "w" (text mode) instead of "wb" (binary mode):

  • On Windows, every 0x0A byte would be automatically translated to 0x0D 0x0A, silently corrupting the ciphertext.
  • Some library implementations may drop bytes that don't map to valid characters.
  • When you later decrypt the file, the byte sequence no longer matches what you wrote, so the decryption output is garbled.

On Linux and macOS the difference is less visible, but using "rb"/"wb" is still the correct habit for any data that isn't guaranteed to be plain text.

🐛 Common Pitfalls

  • Using text mode: The single most common bug. Always use "rb" and "wb" when the output isn't guaranteed to be text.
  • Declaring ch as char: fgetc returns int. If you declare ch as char, EOF (-1) may not be detected on systems where char is unsigned.
  • Encrypting the file in place: If you open the same file for both reading and writing, you'll corrupt the data. Always write to a different file, then swap if needed.
  • Forgetting the leading space in " %c": Without it, the newline left over from the previous scanf becomes the key — resulting in encryption with key 0x0A instead of the character you typed.
  • Using the wrong key for decryption: XOR is symmetric — decrypt with the same key. A different key produces garbage, not an error.
  • Assuming the encrypted file is text: It isn't. Don't try to open it in a text editor or send it in a text email unless you encode it (e.g., base64).

🔑 Stronger Keys: Multi-Byte XOR

A single-byte key is trivially breakable by frequency analysis: the most common ciphertext byte almost certainly corresponds to the space character or 'e'. A slightly better version uses a multi-byte key repeated over the file:

const char *key = "SECRET"; size_t key_len = strlen(key); size_t i = 0; while ((ch = fgetc(src)) != EOF) { fputc(ch ^ key[i % key_len], dst); i++; }

This still isn't secure against a determined attacker (the key can be recovered by factoring the ciphertext into a Vigenère-style analysis), but it raises the difficulty significantly and demonstrates the concept of key scheduling — a real cryptographic building block.

💡 Tips & Best Practices

  • Use "rb"/"wb" in all encryption programs, even if the input looks like text — encryption always produces binary output.
  • Check both fopen calls for NULL and close the first file before returning on the second's failure.
  • Print the byte count so the user knows the operation actually processed something.
  • Never encrypt the original file in place. Write to a new file, verify the output looks correct, then optionally remove the plaintext.
  • For genuine protection, use OpenSSL's AES-256-GCM API — never roll your own crypto in production.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type mismatches.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 13. Decrypt the Contents of an Encrypted Text File
  • 15. Copy the Contents of One Text File into Another
  • 4. Read and Display the Contents of a Text File
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 10. Replace a Word with Another Word in a Text File   ||   Next Problem: -->> 12. Sort the Lines of a Text File in Alphabetical Order

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.