How to do it…

  1. Open the source file in read-only mode using the following code:
fp = fopen (argv [1],"r");
  1. If the file does not exist or does not have enough permissions, an error message will be displayed and the program will terminate, as shown in the following code:
if (fp == NULL) {
printf("%s file does not exist\n", argv[1]);
exit(1);
}
  1. Open the destination file, the file where the encrypted text will be written, in write-only mode using the following code:
fq = fopen (argv[2], "w");
  1. Read a line from the file and access each of its characters using the following code:
fgets(buffer, BUFFSIZE, fp);
  1. Using the following code, subtract a value of 45 from the ASCII value of each of the characters in the line to encrypt that character:
for(i=0;i<n;i++)
buffer[i]=buffer[i]-45;
  1. Repeat step 5 until the line is over. Once all of the characters in the line are encrypted, write the encrypted line into the destination file using the following code:
fputs(buffer,fq);
  1. Check whether the end of the file has been reached using the following code:
while (!feof(fp))
  1. Close the two files using the following code:
fclose (fp);
fclose (fq);

The preceding steps are shown in the following diagram:

Figure 6.4

The encryptfile.c program to encrypt a file is as follows:

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

#define BUFFSIZE 255
void main (int argc, char* argv[])
{
FILE *fp,*fq;
int i,n;
char buffer[BUFFSIZE];

/* Open the source file in read mode */
fp = fopen (argv [1],"r");
if (fp == NULL) {
printf("%s file does not exist\n", argv[1]);
exit(1);
}
/* Create the destination file. */
fq = fopen (argv[2], "w");
if (fq == NULL) {
perror ("An error occurred in creating the file\n");
exit(1);
}
while (!feof(fp))
{
fgets(buffer, BUFFSIZE, fp);
n=strlen(buffer);
for(i=0;i<n;i++)
buffer[i]=buffer[i]-45;
fputs(buffer,fq);
}
fclose (fp);
fclose (fq);
}

Now, let's go behind the scenes.