Reputation: 818
I'm looking for a word/phrase in a file.txt.
file looks like this:
apple tree '\t' data
apple '\t' data
apple pie '\t' data
Greek '\t' data
Holland ; Netherlands ; The Netherlands '\t' data
I am looking for a char *word
inside this huge file. It gets tricky when I have words like Netherlands
or The Netherlands
and I want to grab that data.
I have broken the problem down into tiny parts. So far I know how many lines the file has and can use that information to fseek to that line. Those parts work independently of this part below.
file_lines = 12325;
// line_index[] every element corresponds to a line in to a line in the file.
char* buffer[256];
FILE fp = fopen(file.txt, "r")
int i, j, k;
for(i = line_index[index_start]; i < line_index[index_end]; i++)
{
fseek(fp, i, SEEK_SET);
fgets(buffer, 256, fp);
if(strstr(buffer, word) != NULL) // word is here
{
// having problems finding the word here
for(j = 0; j < 256; j++)
for(k = 0; k < 256; k++)
{
if(buffer[k] == word[k])
continue;
if(buffer[k] == ' ')
continue;
if(buffer[k] == ';')
break;
if(buffer[k] == '\t')
break;
}
}
}
My biggest problem is making sure the word/phrase is in that line. I can know which potential line has an instance of the word, but if I am looking for apple I might get apple tree if I don't search inside that line correctly.
Please help.
Upvotes: 0
Views: 51
Reputation: 7044
Roughly...
char *tab = strchr(buffer, '\t');
if(tab) *tab = 0;
if(strstr(buffer, word) != NULL) // word is here
{
char *token = strtok(buffer, ";");
int found = 0;
while(token) {
// remove this printf later, but for now it will help you debug
printf("'%s' vs '%s'\n", word, token);
if(strcmp(word, token) == 0) {
found = 1;
break;
}
token = strtok(0, ";");
}
if(found) {
if(tab == 0) {
printf("No data for %s\n", word);
} else {
printf("data is '%s'\n", tab+1);
}
}
Upvotes: 2