We will define two file pointers, fp and fq. We will open the first file that is supplied through the command-line argument in read-only mode, and the second file in write-only mode. If the files cannot be opened in the read-only mode and write-only mode, respectively, an error message will be displayed and the program will terminate. The file that opens in read-only mode is pointed at by the fp file pointer and the file that opens in write-only mode is pointed at by the file fq file pointer.
We will set a while loop to execute, which will read all the lines from the file pointed at by the fp pointer one by one. The while loop will continue to execute until the end of the file pointed at by fp is reached.
.Within the while loop, a line is read and is assigned to the buffer string variable. The length of the line is computed. We will then set a for loop is set to execute up until the end of the line; that is, each character of the line is accessed. We will add the value 45 to the ASCII value of each character to encrypt it. Thereafter, we will write the decrypted line into the second file. The file is pointed at by the fq file pointer. When the file from which the content was read is finished with, both the file pointers are closed to release the resources allocated to both the files.
Let's use GCC to compile the decryptfile.c program, as shown in the following statement:
D:\CBook>gcc decryptfile.c -o decryptfile
Assume the encrypted file is named encrypted.txt. Let's see the encrypted text in this file:
D:\CBook>type encrypted.txt
≤4@≤GEL<A:≤GB≤6E84G8≤4≤F8DH8AG<4?≤9<?8≤<G≤<F≤G;EBH:;≤≤CEB:E4@@<A:≤≤≤G≤<F≤I8EL≤;BG≤GB74L≤;4I8≤4≤64G≤≤7B≤LBH≤?<>8≤4A<@4?F≤≤≤≤G≤@<:;G≤E4<A';4A>≤LBH≤5L8
If you get no errors or warnings while compiling the file, this means that the decryptfile.c program has been compiled into an executable file, decryptfile.exe. Assume that an encrypted file by the name of encrypted.txt already exists and you want to decrypt it into another file, originalfile.txt. So, let's run the executable, decryptfile.exe, to decrypt the encrypted.txt file:
D:\CBook>decryptfile encrypted.txt originalfile.txt
Let's see the contents of orignalfile.txt to see whether it contains the decrypted version of the file:
D:\CBook>type originalfile.txt
I am trying to create a sequential file. it is through C programming. It is very hot today. I have a cat. do you like animals? It might rain. Thank you. bye
Voila! You can see that originalfile.txt contains the decrypted file.