在c中的文本文件中应用二进制搜索,逐行文本

问题描述 投票:0回答:1

我试图在文本文件中搜索一个单词,但我得到了一些成功,但代码并不总是有效。它只是我不明白它为什么它不在循环内工作,但我手动操作时工作。

我知道很多东西要看,但请任何人帮助我。

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>

void main()
{
    FILE *fp;
    fp=fopen("testdictionary.txt","r");

    char word[]="her";
    char line[7];
    int n;
    int upper_limit=48;
    int lower_limit=0;
    int result=-1;

    while(result!=0) {
        n=(upper_limit+lower_limit)/2;
        printf("Value of n:%d ",n);
        fseek(fp,n,SEEK_SET);

        // setting the file pointer to the beginning of the word. --
        fseek(fp,-1,SEEK_CUR);
        char tst;
        do {
            fseek(fp,-1,SEEK_CUR);
            if(ftell(fp)==0) {
                break;
            }

            tst=fgetc(fp);
            if(tst=='\n') {
                break;
            }

            fseek(fp,-1,SEEK_CUR);
        } while(tst!='\n');
        //----------------------------------------------------------

        fgets(line,7,fp);
        result=strcmp(line,strcat(word,"\n"));
        printf(" Result:%d ",result);

        if(result==1) {
            upper_limit=n;
            printf("Required 'word' is above the line of text.\n");
        }
        else if(result==-1) {
            lower_limit=n;
            printf("Required 'word' is below the line of text.\n");
        }
        else if(result==0) {
            printf("Word found");
        }
    }
}

我的文字文件

aoo
bpp
cas
dzx
edf
fvb
gty
her
iwe
jqw

输出(当我运行上面的代码时。)

Value of n:24  Result:-1 Required 'word' is below the line of text.
Value of n:36  Result:-1 Required 'word' is below the line of text.
Value of n:1322  Result:1 Required 'word' is above the line of text.
Value of n:329639  Result:1 Required 'word' is above the line of text.
Value of n:84052197

我不明白的部分是,如果我手动输入n = 36,结果显示0并找到单词。但是当我尝试自动搜索时,即使第二步后n的值变为36,循环也不会不要破坏并给出奇怪的和大的n值。

因此,当我自己输入n = 36(如下所示)时,我得到了“她”这个词的预期输出。

while(result!=0)
{
    // n=(upper_limit+lower_limit)/2;
    n=36;
    printf("Value of n:%d ",n);
    fseek(fp,n,SEEK_SET);

产量

Value of n:36  Result:0 Word found
Process returned 10 (0xA)   execution time : 0.141 s
Press any key to continue.

我不知道这是否应该如何进行二分查找,但这就是我所知道的。我只是编程的初学者。

c search text-files binary-search file-handling
1个回答
3
投票

功能strcmp不会特别返回-11(虽然它可能会这样做)。它返回值0< 0> 0

也在

result = strcmp(line, strcat(word, "\n"));

你不能连接到任何东西

char word[] ="her";

因为阵列没有空间。最好从文件字符串中删除换行符,而不是将其添加到目标字符串中。

即使你可以,你也会在每次迭代中添加另一个换行符。所以我建议

fgets(line, 7, fp);
line [ strcspn(line, "\r\n") ] = '\0';      // truncate any newline
result = strcmp(line, word);
if(result > 0) {
    upper_limit = n;
    printf("Required 'word' is above the line of text.\n");
}
else if(result < 0) {
    lower_limit = n;
    printf("Required 'word' is below the line of text.\n");
}
else {   // no other possibility
    printf("Word found");
}
© www.soinside.com 2019 - 2024. All rights reserved.