In this tutorial you will learn about the C Program to Encrypt & Decrypt a File and its application with practical example.
C Program to Encrypt & Decrypt a File
In this tutorial, you will learn about the C Program to Encrypt & Decrypt a File with a practical example.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Concepts of while loop.
- Conditional Statements in C programming.
- Using file functions of c language.
Program to Encrypt & Decrypt a File
As we all know the file is a collection of characters, integers, and many data types. In strings, only one variable is declared which can store multiple values. First will take the file from the user. Then will encrypt that file so that anyone can not read it directly. The C programming language has many pre-defined functions for file manipulation. but in today’s tutorial, we will Encrypt & Decrypt a File.
With the help of this program, we can Encrypt & Decrypt a File
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input file from the user. 3. Reading the file. 4. <strong>Encrypt & Decrypt a File</strong>. 5. Printing the results data. 6. End program. |
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
#include <stdio.h> #include <stdlib.h> void main() { //declaring the variable for the program char fname[20], ch; FILE *fn, *fne; printf("\n\n Encrypt a text file :\n"); printf("--------------------------\n"); //taking input from the user printf(" Input the name of file to encrypt : "); scanf("%s",fname); fn=fopen(fname, "r"); if(fn==NULL) { printf(" File does not exists or error in opening..!!"); exit(1); } fne=fopen("temp.txt", "w"); if(fne==NULL) { printf(" Error in creation of file temp.txt ..!!"); fclose(fn); exit(2); } while(1) { ch=fgetc(fn); if(ch==EOF) { break; } else { ch=ch+100; fputc(ch, fne); } } fclose(fn); fclose(fne); fn=fopen(fname, "w"); if(fn==NULL) { //printing the output printf(" File does not exists or error in opening..!!"); exit(3); } fne=fopen("temp.txt", "r"); if(fne==NULL) { printf(" File does not exists or error in opening..!!"); fclose(fn); exit(4); } while(1) { ch=fgetc(fne); if(ch==EOF) { break; } else { fputc(ch, fn); } } printf(" File %s successfully encrypted ..!!\n\n", fname); fclose(fn); fclose(fne); } |
Output:-
In the above program, we have first initialized the required variable.
- *fn = it will hold the address value.
- ch = it will hold the character value.
- fname[20] = it will hold the string value of the file name.
- *fne = it will hold the address value.
Taking Input file from the user.
Reading the file.
Encrypting the file.
Printing output.