In: Computer Science
IN C LANGUAGE
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> // For exit()
#include <ctype.h>
int main(int argc,char* argv[])
{
FILE *inputfptr, *ouputfptr;
char c;
// Open one file for reading
inputfptr = fopen(argv[1], "r");
if (inputfptr == NULL)
{
printf("Cannot open file %s \n",
argv[1]);
exit(0);
}
// Open another file for writing
ouputfptr = fopen(argv[2], "w");
if (ouputfptr == NULL)
{
printf("Cannot open file %s \n",
argv[2]);
exit(0);
}
// Read contents from file
c = fgetc(inputfptr);
int k = 0;
while (c != EOF)
{
char temp[50];
if(c!=' ')
{
temp[k++] = c;
}
else
{
int t = 1;
for(int m=0;m<k;m++)
{
if(isalpha(temp[m])){}
else{t=0;break;}
}
if(t==1)
{
for(int m=0;m<k;m++)
{
fputc(temp[m], ouputfptr);
}
fputc(' ', ouputfptr);
}
k=0;
}
c = fgetc(inputfptr);
}
printf("\nContents copied to %s", argv[2]);
fclose(inputfptr);
fclose(ouputfptr);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
THE SAME PROGRAMME WITHOUT COMMAND LINE ARGUMENTS
#include <stdio.h>
#include <stdlib.h> // For exit()
#include <ctype.h>
int main(int argc,char* argv[])
{
FILE *inputfptr, *ouputfptr;
char c;
// Open one file for reading
inputfptr = fopen("example.txt", "r");
if (inputfptr == NULL)
{
printf("Cannot open file %s \n",
"example.txt");
exit(0);
}
// Open another file for writing
ouputfptr = fopen("output.txt", "w");
if (ouputfptr == NULL)
{
printf("Cannot open file %s \n",
"output.txt");
exit(0);
}
// Read contents from file
c = fgetc(inputfptr);
int k = 0;
while (c != EOF)
{
char temp[50];
if(c!=' ')
{
temp[k++] = c;
}
else
{
int t = 1;
for(int m=0;m<k;m++)
{
if(isalpha(temp[m])){}
else{t=0;break;}
}
if(t==1)
{
for(int m=0;m<k;m++)
{
fputc(temp[m], ouputfptr);
}
fputc(' ', ouputfptr);
}
k=0;
}
c = fgetc(inputfptr);
}
printf("\nContents copied to %s", "output.txt");
fclose(inputfptr);
fclose(ouputfptr);
return 0;
}