I am trying to program a clone for the Unix command fgrep in C for my CSC class and I am having trouble in this part of my program. It is the part where I search for the specified word in a line (which was attained by fgets and sent to the function when called). It is simply supposed to return 1 if the word was found in the line, or 0 if it was not. I may not be going about this in the best way, but this is what I have:
Code:
int searchLine(char *line, char query[]){
int j;
int i = 0;
int pos = 0;
char tempWord[BUFL];
initString(tempWord, BUFL);
printf("\nQuerying for %s(%d) in:\n %s\n", query, strlen(query), line);
while(1){
if(line[i] == '\n'){
break;
} else if(line[i] == ' '){
printf("*** Space Found @ pos %d\n", i);
initString(tempWord, BUFL);
pos = 0;
for(j = 0; j < strlen(query); j++){
if(tempWord[j] != query[j]){
i++;
break;
}
if(j == strlen(query) - 1){
printf("*** Search Sucess");
return 1;
}
}
} else {
tempWord[pos] = line[i];
printf("Pos: %d | String=%s\n", pos, tempWord);
i++;
}
pos++;
if(i > MAXLEN){
break;
}
}
return 0;
}
There are a couple of debugging prints in it, which should not effect the actual running of the code. The function initString simply fills the entire string with NUL bytes (probably should be called clearString).
Any help will be greatly appreciated.
EDIT: I didn't give an example of the output of the program:
Code:
Querying for chicken(7) in:
alksdf;alkjsf alksdfjdk chicken sdfdsf
Pos: 0 | String=a
Pos: 1 | String=al
Pos: 2 | String=alk
Pos: 3 | String=alks
Pos: 4 | String=alksd
Pos: 5 | String=alksdf
Pos: 6 | String=alksdf;
Pos: 7 | String=alksdf;a
Pos: 8 | String=alksdf;al
Pos: 9 | String=alksdf;alk
Pos: 10 | String=alksdf;alkj
Pos: 11 | String=alksdf;alkjs
Pos: 12 | String=alksdf;alkjsf
*** Space Found @ pos 13
Pos: 1 | String=
Pos: 2 | String=
Pos: 3 | String=
It keeps going without anything in the tempWord variable (which is, I assume, result of initString), but I thought it would ad the next word (the chars in "line" after a space is found) to tempWord starting at "pos = 0"
Sorry for the long post