C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Decrypt file content

C program to decrypt a file that was encrypted using the Caesar cipher technique (same logic as the encryption program, but in reverse).

This makes a perfect pair for your “Encrypt/Decrypt File Content” examples in your File Handling + Security chapter.

 

C Program: Decrypt File Content

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    FILE *source, *target;

    char sourceFile[100], targetFile[100];

    char ch;

    int key;

 

    // Step 1: Input filenames and decryption key

    printf("Enter encrypted file name: ");

    scanf("%s", sourceFile);

 

    printf("Enter output (decrypted) file name: ");

    scanf("%s", targetFile);

 

    printf("Enter decryption key (same key used for encryption): ");

    scanf("%d", &key);

 

    // Step 2: Open files

    source = fopen(sourceFile, "r");

    if (source == NULL) {

        printf("Unable to open encrypted file!\n");

        return 0;

    }

 

    target = fopen(targetFile, "w");

    if (target == NULL) {

        printf("Unable to create output file!\n");

        fclose(source);

        return 0;

    }

 

    // Step 3: Decrypt file

    while ((ch = fgetc(source)) != EOF) {

        fputc(ch - key, target); // reverse the encryption

    }

 

    fclose(source);

    fclose(target);

 

    printf("File '%s' decrypted successfully to '%s' using key %d.\n", sourceFile, targetFile, key);

    return 0;

}

Output

 
Encrypted File  (encrypted.txt):
 
Mjqqt%Xyizsjyx
H%Uwtlwfrrnsl%nx%Utajwzq

Key: 5

Output  (decrypted.txt):

Hello Students
C Programming is Powerful