首页 > 解决方案 > C 编程中的蛮力搜索,在 C 编程中读取 .fna 文件

问题描述

我能够阅读 .fna 并搜索我想要的模式。但是在我阅读文件之后,它是逐行而不是全部阅读。如何提取 .fna 文件并将其存储为 C 编程中的变量?下面是我的代码和我得到的输出:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHAR 70000

void search(char* pattern, char* text)
{

    int M = strlen(pattern);
    int N = strlen(text);

    for (int x = 0; x <= N - M; x++) {
        int y;

        for (y = 0; y < M; y++)
            if (text[x + y] != pattern[y])
                break;

        if (y == M)
        {
            printf("Found pattern at position %d \n", x+1);
        }
    }}

int main()
{

    FILE *fp;
    char str[MAXCHAR];
    char pattern[] = "GTTCTTT";
    char* filename = "D:\\Desktop\\NC_007409.fna";
    fp = fopen(filename, "r");

    if (fp == NULL){
        printf("Could not open file %s",filename);
        return 1;
    }

    while (fgets(str, MAXCHAR, fp) != NULL)
        search(pattern, str);
        return 0;
}

我得到的输出

标签: ccodeblocksbrute-forcestring-search

解决方案


您可以通过两种方式将文件的内容作为字节数组获取:

手动分配数组(简单方式)

  1. 获取文件大小;
  2. 使用文件大小为文件内容分配内存;
  3. 将所有内容读取到文件到分配的内存中。

使用文件映射(高级方式)

内存映射文件的好处是提高 I/O 性能,尤其是在用于大文件时。对于小文件,内存映射文件可能会导致松弛空间的浪费,因为内存映射总是与页面大小对齐,页面大小通常为 4 KiB。


推荐阅读