C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Encrypt file content

C program to encrypt file content (basic encryption example using character shifting).

This kind of program is excellent for your File Handling + Security Concepts chapter — showing how to manipulate file contents byte by byte.

 

C Program: Encrypt 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 encryption key

    printf("Enter source file name: ");

    scanf("%s", sourceFile);

 

    printf("Enter target (encrypted) file name: ");

    scanf("%s", targetFile);

 

    printf("Enter encryption key (integer): ");

    scanf("%d", &key);

 

    // Step 2: Open files

    source = fopen(sourceFile, "r");

    if (source == NULL) {

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

        return 0;

    }

 

    target = fopen(targetFile, "w");

    if (target == NULL) {

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

        fclose(source);

        return 0;

    }

 

    // Step 3: Encrypt and write to target

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

        fputc(ch + key, target); // simple Caesar cipher encryption

    }

 

    fclose(source);

    fclose(target);

 

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

    return 0;

}

Output

 
 
Input File  (message.txt):
 
Hello Students
C Programming is Powerful

Encryption key: 5

Output File  (encrypted.txt):

Mjqqt%Xyizsjyx
H%Uwtlwfrrnsl%nx%Utajwzq

Decryption Note: To decrypt, you just reverse the process — subtract the key instead of adding it:

fputc(ch - key, target);