如何在c中搜索文本文件中的特定字符串

时间:2015-12-07 11:21:43

标签: c string text-files file-handling

我需要从文本文件的内容中找到特定的字符串。用户输入他们正在寻找的字符串,程序搜索打开的文本文件以找到该字符串。可以使用C吗?

这是应该使用功能扩展的基本代码:

void exam()
{
char name[50], rollno[50];
FILE *search;
printf("\t\t________________________________");
printf("\n\n\t\t\tPortal Examination");
printf("\n\t\t_______________________________");
printf("\n\tEnter Name : ");
scanf("%s", name);
search = fopen("Students.txt", "r");
}

2 个答案:

答案 0 :(得分:0)

  

将文件(部分)读入内存,然后使用标准字符串   函数strstr()来搜索   字符串(在循环中)。 - pmg

renderUI

答案 1 :(得分:-1)

不确定。实际上,这是我为another question生成的一个确切示例:

void find_match(FILE *input_file, char const *needle, size_t needle_size) {
    char input_array[needle_size];
    size_t sz = fread(input_array, 1, needle_size, input_file);
    if (sz != needle_size) {
        // No matches possible
        return;
    }

    setvbuf(input_file, NULL, _IOFBF, BUFSIZ);
    unsigned long long pos = 0;
    for (;;) {
        size_t cursor = pos % needle_size;
        int tail_compare = memcmp(input_array, needle + needle_size - cursor, cursor),
            head_compare = memcmp(input_array + cursor, needle, needle_size - cursor);
        if (head_compare == 0 && tail_compare == 0) {
            printf("Match found at offset %llu\n", pos);
        }
        int c = fgetc(input_file);
        if (c == EOF) {
            break;
        }
        input_array[cursor] = c;
        pos++;
    }
}