w3resource logo


C Programming Exercises

C Exercises: Decrypt a previously encrypted file

Secondary Nav

C File Handling : Exercise-14 with Solution

Write a program in C to decrypt a previously encrypted file file.

 Assume that, the content of the file test.txt was  :                                                                       
Welcome to w3resource.com. 

After encryption, the content of the file is : 
������Ʉ�ӄۗ�������ɒ��ђn

Test Data :
Input the name of file to decrypt : test.txt
Expected Output :

The file test.txt decrypted successfully..!!

Now, if you read the file test.txt you will see the following :

Welcome to w3resource.com.

C Code:

#include <stdio.h>
#include <stdlib.h>

void main()
{
	char ch, fname[20];
	FILE *fpts, *fptt;
	
	printf("\n\n Decrypt a text file :\n");
	printf("--------------------------\n"); 	
	
	printf(" Input the name of file to decrypt : ");
	scanf("%s",fname);	
	
	fpts=fopen(fname, "w");
	if(fpts==NULL)
	{
		printf(" File does not exists or error in opening..!!");
		exit(7);
	}
	fptt=fopen("temp.txt", "r");
	if(fptt==NULL)
	{
		printf(" File does not exists or error in opening..!!");
		fclose(fpts);
		exit(9);
	}
	while(1)
	{
		ch=fgetc(fptt);
		if(ch==EOF)
		{
			break;
		}
		else
		{
			ch=ch-100;
			fputc(ch, fpts);
		}
	}
	printf(" The file %s decrypted successfully..!!\n\n",fname);
	fclose(fpts);
	fclose(fptt);
}

Flowchart :

Flowchart: Decrypt a previously encrypted file

C Practice online:


#include <stdio.h>
#include <stdlib.h>

void main()
{
	char ch, fname[20];
	FILE *fpts, *fptt;
	
	printf("\n\n Decrypt a text file :\n");
	printf("--------------------------\n"); 	
	
	printf(" Input the name of file to decrypt : ");
	scanf("%s",fname);	
	
	fpts=fopen(fname, "w");
	if(fpts==NULL)
	{
		printf(" File does not exists or error in opening..!!");
		exit(7);
	}
	fptt=fopen("temp.txt", "r");
	if(fptt==NULL)
	{
		printf(" File does not exists or error in opening..!!");
		fclose(fpts);
		exit(9);
	}
	while(1)
	{
		ch=fgetc(fptt);
		if(ch==EOF)
		{
			break;
		}
		else
		{
			ch=ch-100;
			fputc(ch, fpts);
		}
	}
	printf(" The file %s decrypted successfully..!!\n\n",fname);
	fclose(fpts);
	fclose(fptt);
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program