Code:
#include <stdio.h>
#define MAX_LINHA 128
/* Compares the words received in the command line with those
* in the array, char by char (the program must detect a word as
* a subsequence of another word, for example, "um" is a subsequence
* of "uma"). Returns the counter.
*/
int comparaux(int n, char palavra[], char linha[], int pos_linha, int pos_palavra)
{
int j=0, p=pos_palavra, m=pos_linha;
while(linha[m]!='\n')
{
if(palavra[p] == '\0')
{
n=n+1;
comparaux(n, palavra, linha, m, 0);
}
else
{
if(linha[m]==palavra[p])
comparaux(n,palavra, linha, m+1,p+1);
else
comparaux(n,palavra, linha, m+1,p);
}
}
return n;
}
/* A main counter(contprincipal) is declared and inicialized.
* The variable count as the value of argc.
* Calls the comparaux function with the current line and argv
*/
int compara_palavras(char *palavras[],int count,char linha[])
{
int cont_principal=0;
int j;
for(j=1; j<=(count-2); ++j)
cont_principal=(comparaux(0, palavras[j], linha,0,0))+cont_principal;
return cont_principal;
}
/* Stores the current line in an array called linha (line)
* After storing ,calls the function compara_palavras (compare words)
* with an if clause.If the clause is true, it prints the line
* stored in the array, and the counter.Goes to the next line.
*/
int guarda_linha(int protese ,char *grepa[])
{
int i=0, j=0;
char linha[MAX_LINHA];
char d;
int c=0;
if((d=getchar()) != EOF)
{
while ((d=getchar()) != '\n' && d!=EOF)
{
linha[i]=d;
++i;
}
linha[i++]='\n';
if((c=compara_palavras(grepa,protese,linha))!=0)
{
printf("LINHA: ");
for (j=0; linha[j]!='\n'; ++j)
putchar(linha[j]);
putchar('\n');
printf("CONTAGEM: %d\n", c);
if (d != EOF)
guarda_linha(protese,grepa);
}
else guarda_linha(protese,grepa);
}
return 1;
}
/* The program must test the command line*/
main(int argc, char *argv[])
{
fflush(stdout);
if(argc <=2)
puts("Argumentos inválidos.");
else
guarda_linha(argc, argv);