在文件中搜索字符串

时间:2012-11-24 15:37:07

标签: c file search

我必须在文件中搜索输入的字符串,但下面的代码不起作用。它总是说“无法在字典中找到。文件的内容(称为Dictionary.txt)如下:

pow
jaw
pa$$word

代码是:

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

#define MAX 30

main()
{
    char inPassword[MAX + 1];
    printf("\nEnter a password: ");
    gets(inPassword);

    printf("\n\nYou entered: %s, please wait, checking in dictionary.\n\n",inPassword);
    checkWordInFile("Dictionary.txt",inPassword);

    printf("\n\n\n");
    system("pause");
}//end of main


void checkWordInFile(char *fileName, char *password);
{
    char readString[MAX + 1];
    FILE *fPtr;
    int iFound = -1;
    //open the file
    fPtr = fopen(fileName, "r");

    if (fPtr == NULL)
    {
        printf("\nNo dictionary file\n");
        printf("\n\n\n");
        system("pause");
        exit(0);    // just exit the program
    }


    while(fgets(readString, MAX, fPtr))
    {
            if(strcmp(password, readString) == 0)
        {
            iFound = 1;
        }

    }

    fclose(fPtr);

    if( iFound > 0 )
    {
        printf("\nFound your word in the dictionary");
    }
    else
    {
        printf("\nCould not find your word in the dictionary");
    }


}

2 个答案:

答案 0 :(得分:3)

除非EOF,否则

fgets()会将\ n留在字符串的末尾。这解决了它:

while(fgets(readString, MAX, fPtr))
{
    size_t ln = strlen(readString);
    if (ln && readString[ln-1] == '\n') { readString[ln-1] = 0; --ln; }
    if(ln && strcmp(password, readString) == 0)
    {
        iFound = 1;
    }

}

答案 1 :(得分:0)

如何更改此函数以搜索此文件包含的子字符串?例如,如果我输入一个单词“repow234”,我应该收到一条消息,说这是不正确的,因为“pow”是文件,不能使用

这不起作用:

while(fgets(readString, MAX, fPtr))
{
    if (strstr( password, readString) != NULL)
    {
        iFound = 1;
    }
}

fclose(fPtr);

if( iFound > 0 )
{
    printf("\nThis password cannot be used because it contains the word in the dictionary");
}
else
{
    printf("\nThis password can be used");
}