In: Computer Science
16.15 Lab 5: filter
Name this program filter.c.
Examples
./a.out example.txt output.txt
example.txt | output.txt |
---|---|
The Quick Brown Fox Jumps over the Lazy Old Dog. ALABAMA? Roll Tide!!! P2P 1831 (UA) | The Quick Brown Fox Jumps over the Lazy Old Roll |
./a.out does_not_exist.txt output.txt Cannot open file 'does_not_exist.txt'
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char** argv)
{
FILE *fptr1, *fptr2;
char c;
char str[400];
char newString[20][20];
char b[20];
// Open one file for reading
fptr1 = fopen(argv[1], "r");
if (fptr1 == NULL || fptr1 == 0)
{
printf("Cannot open file %s \n", argv[1]);
}
// Open another file for writing
fptr2 = fopen(argv[2], "w");
if (fptr2 == NULL || fptr2 == 0)
{
printf("Cannot open file %s \n", argv[2]);
}
// Read contents from file
c = fgetc(fptr1);
int x=0;
while (c != EOF)
{ str[x++]=c;
c = fgetc(fptr1);
}
int i,j,ctr;
j=0; ctr=0;
for(i=0;i<=(strlen(str));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str[i]==' '||str[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str[i];
j++;
}
}
for(j=0;j<=ctr;j++)
{
for(i=0;i<=(strlen(newString[j])-1);i++)
{
if( isalpha(newString[j][i])==0)
{
b[j]='*';
break;
}
}
}
char space[1]=" ";
for(j=0;j<ctr;j++)
{
if(b[j]!='*'){
for(i=0;i<=(strlen(newString[j])-1);i++)
{
fputc(newString[j][i], fptr2);
}
fputc(space[0], fptr2);
}
}
fclose(fptr1);
fclose(fptr2);
return 0;
}