c - 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;
}
解决方案
您可以通过两种方式将文件的内容作为字节数组获取:
手动分配数组(简单方式)
- 获取文件大小;
- 使用文件大小为文件内容分配内存;
- 将所有内容读取到文件到分配的内存中。
使用文件映射(高级方式)
内存映射文件的好处是提高 I/O 性能,尤其是在用于大文件时。对于小文件,内存映射文件可能会导致松弛空间的浪费,因为内存映射总是与页面大小对齐,页面大小通常为 4 KiB。
推荐阅读
- android-studio - 在 Android Studio 上颤振升级和颤振降级后热重启/重新加载中断
- node.js - Twitter活动账号api返回403
- javascript - Svelte:动态导入组件不起作用
- javascript - FabricJS 如何确保注释粘在页面上的位置而不是视口(可能是纯 JS/CSS 问题)
- excel - 如何提高代码的性能
- reactjs - 带有webpack模板条件`类名`的Reactjs不起作用
- java -
> - react-native - 导入 Web 组件时出现 React-native 错误
- flutter - Flutter:在 null 上调用了方法“toDouble”
- reactjs - 错误:使用 webpack-cli 4.2.0 找不到模块“webpack-cli/bin/config-yargs”