在C中匹配哈希

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

我是C的新手,我目前正在练习编写一个允许用户搜索文本文件中写入的哈希的程序。我想出了以下程序:

HashMatch.c

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

//Declaring Functions
int searchstringinfile(char *string, char *filename);
void UsageInfo(char *filename);

//Display usage info on arguements for program
void UsageInfo(char *filename) {
    printf("Usage: %s <file> <string>\n", filename);

}

int searchstringinfile(char *filename, char *string) {
    //Define File
    FILE *userfile;

    int linenumber = 1;
    int search_result = 0;
    char temp[10000];

    //Error handling for invalid file
    if((userfile = fopen(filename, "r")) == NULL) {
        return(-1);
    }


    //Matching words line-by-line
    while(fgets(temp, 10000, userfile) != NULL) {
        if((strstr(temp, string)) != NULL) {
        //Display line in which matched word is found
            printf("A match found on line: %d\n", linenumber);
            printf("\n%s\n", temp);
            search_result++;
    }
    linenumber++;
}


    // Display message if no matches are found
    if(search_result == 0) {
        printf("\nSorry, couldn't find a match.\n");
    }

    //Closes the file.
    if(userfile) {
        fclose(userfile);
    }
    return(0);
}


//main function.
int main(int argc, char *argv[]) {
    int result, errcode;
    //Display format for user to enter arguements and
    //End program if user does not enter exactly 3 arguements
    if(argc < 3 || argc > 3) {
        UsageInfo(argv[0]);
        exit(1);
}


    system("cls");
//Pass command line arguements into searchstringinfile
    result = searchstringinfile(argv[1], argv[2]);
//Display error message
        if(result == -1) {
            perror("Error");
            printf("Error number = %d\n", errcode);
            exit(1);
    }
    return(0);
}

我还提出了一个包含一个字符串和一个哈希的文件:

Hstekstktst

$1$$t8TX0OHN6Wsx6vlPZNKik1
Ice-Cream
I SCREAM FOR Ice-Cream !

如果我要搜索冰淇淋这个词:

./test hashtext Ice-Cream

我能找到包含所述单词的行:

A match found on line: 2

Ice-Cream

A match found on line: 3

I SCREAM FOR Ice-Cream !

但是,如果我要在文本中搜索哈希,我无法这样做。任何人都可以告诉我为什么我无法搜索哈希并指导我完成允许我这样做的步骤?

谢谢。

c hash
2个回答
0
投票

你的哈希字符串里面有'$'。 Bash认为它是一个特殊的角色。需要转义特殊字符才能删除这些字符的特殊含义。

根据具体情况,您可以执行以下任一操作来处理它们:

  1. 使用\单独转义特殊字符。你的输入字符串看起来像\$1\$\$t8TX0OHN6Wsx6vlPZNKik1
  2. 使用'从整个字符串中转义特殊字符。你的输入字符串看起来像'$1$$t8TX0OHN6Wsx6vlPZNKik1'
  3. 通过重定向从stdin加载字符串。但是,您需要为此编辑程序。你不需要逃避角色。

这是bash中许多特殊字符的完整列表:https://docstore.mik.ua/orelly/unix/upt/ch08_19.htm


0
投票

从评论你似乎同意你的命令行有$,你不需要在代码中处理它,而不是从shell传递它你需要逃避它们像:

./test hashtext \$1\$\$t8TX0OHN6Wsx6vlPZNKik1
© www.soinside.com 2019 - 2024. All rights reserved.