- Open the sequential file in read-only mode using the following code:
fp = fopen (argv [1],"r");
- If the file does not exist or does not have enough permissions, an error message will be displayed and the program will terminate. Set this up using the following code:
if (fp == NULL) {
printf("%s file does not exist\n", argv[1]);
exit(1);
}
- One line is read from the file, as shown in the following code:
fgets(buffer, BUFFSIZE, fp);
- Each character of the line is accessed and checked for the presence of periods, as shown in the following code:
for(i=0;i<n;i++)
if(buffer[i]=='.')
- If a period is found, the character following the period is checked to confirm whether it is in uppercase, as shown in the following code:
if(buffer[i] >=97 && buffer[i] <=122)
- If the character following the period is in lowercase, a value of 32 is subtracted from the ASCII value of the lowercase character to convert it into uppercase, as shown in the following code:
buffer[i]=buffer[i]-32;
- If the line is not yet over, then the sequence from step 4 onward is repeated till step 6; otherwise, the updated line is displayed on the screen, as shown in the following code:
puts(buffer);
- Check whether the end of file has been reached using the following code. If the file is not over, repeat the sequence from step 3:
while(!feof(fp))
The preceding steps are pictorially explained in the following diagram (Figure 5.1):
Figure 5.1
The convertcase.c program for converting a lowercase character found after a period in a file into uppercase is as follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFSIZE 255
void main (int argc, char* argv[])
{
FILE *fp;
char buffer[BUFFSIZE];
int i,n;
fp = fopen (argv [1],"r");
if (fp == NULL) {
printf("%s file does not exist\n", argv[1]);
exit(1);
}
while (!feof(fp))
{
fgets(buffer, BUFFSIZE, fp);
n=strlen(buffer);
for(i=0;i<n;i++)
{
if(buffer[i]=='.')
{
i++;
while(buffer[i]==' ')
{
i++;
}
if(buffer[i] >=97 && buffer[i] <=122)
{
buffer[i]=buffer[i]-32;
}
}
}
puts(buffer);
}
fclose(fp);
}
Now, let's go behind the scenes.