c - 在文件中搜索文本
问题描述
我写了这个但它没有用:我有一个名为contact.txt的文件,我有一些文本,我如何在文件中搜索文本,如果匹配应该打印出c中的文本
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
char don[150];
int tr,y;
FILE *efiom;
//this is the input of don blah blah blah
printf("Enter a search term:\n");
scanf("%s",&don);
//this is for the reading of the file
efiom =fopen("efiom.txt","r");
char go[500];
//OMO i don't know what is happeing is this my code
while(!feof(efiom))
{
// this is the solution for the array stuff
void *reader = go;
tr = strcmp(don,reader);
fgets(go, 500 ,efiom);
}
// my if statement
if(tr == 0)
{
printf("true\n");
}
else
{
printf("false\n");
}
fclose(efiom);
return 0;
}
解决方案
只需使用以下功能string.h
:
char * strstr (char * str1, const char * str2 );
返回指向 str1 中第一次出现 str2 的指针,如果 str2 不是 str1 的一部分,则返回空指针。
匹配过程不包括终止的空字符,但它会停在那里。
将文件读入一个字符串 ( char*
)。你可以使用这个:
FILE* fh = fopen(filename, "r");
char* result = NULL;
if (fh != NULL) {
size_t size = 1;
while (getc(fh) != EOF) {
size++;
}
result = (char*) malloc(sizeof(char) * size);
fseek(fh, 0, SEEK_SET); //Reset file pointer to begin
for (size_t i = 0; i < size - 1; i++) {
result[i] = (char) getc(fh);
}
result[size - 1] = '\0';
fclose(fh);
}
推荐阅读
- php - 使用 cron 调用 php 脚本的问题
- kubernetes - 使用 Argo Workflows 创建队列系统
- leaflet - tileLayer和控件的Leaflet js问题
- django - django - 从用户发布的基于类的视图
- parsing - 解析器/语法:嵌套规则中的 2x 括号
- xamarin.forms - 从 xamarin 表单中的 xml 响应的 url 获取多个图像
- redis - 无法在我的本地机器上启动 Sidekiq:在 redis 上连接到 Redis 时出错:6379 (SocketError)
- java - 什么情况下会使用 nextLine() 创建 nosuchelementexception?
- ios - iOS 14 中的 WKContentRuleListStore.default() 崩溃
- windows-installer - CX_FREEZE 窗口 - AttributeError:“NoneType”对象没有属性写入