0

我正在寻找 file.txt 中的单词/短语。

文件如下所示:

    apple tree '\t' data
    apple '\t' data
    apple pie '\t' data
    Greek '\t' data
    Holland ; Netherlands ; The Netherlands '\t' data

我正在char *word这个巨大的文件中寻找一个。当我有Netherlandsor之类的词The Netherlands并且我想获取该数据时,这会变得很棘手。

我已将问题分解为小部分。到目前为止,我知道该文件有多少行,并且可以使用该信息 fseek 到该行。这些部分独立于下面的这部分工作。

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;
       }

   }
}

我最大的问题是确保单词/短语在该行中。我可以知道哪个潜在的行有一个单词的实例,但是如果我正在寻找苹果,如果我没有正确地在该行内搜索,我可能会得到苹果树。

请帮忙。

4

1 回答 1

2

大致...

   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);
           }
       }
于 2013-11-10T18:11:22.880 回答