c - 如何在文件中找到特定的单词?
问题描述
我想检查文件中是否包含“Title1, title2, title 3, title4”字样。如果文件中有这些单词,我想打印“we found the %s word in file”。
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(int argc, char const *argv[])
{
char word[4][20]={"tittle1","tittle2","tittle3","tittle4"};
char *string;
int k;
FILE *in_file = fopen("abce.txt", "r");
if (in_file == NULL)
{
printf("Error file missing\n");
}
else{
printf("enter a array number that you want find in file");
scanf("%d",&k);
while(!feof(in_file))
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word[k-1])){
printf("we found the word %s in the file \n",string );
}
}
}
return 0;
}
但我无法正确编写代码。你能帮我修一下吗?谢谢你的帮助...
解决方案
我不得不做一些重构。
string
是char *
但从未分配过。因此,fscanf
将出现段错误。
word
可能是char *word[]
。
您strcmp
需要连接到printf
您需要rewind
先扫描文件,然后再扫描每个新词。
其他修复...
无论如何,这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
char *word[] = { "tittle1", "tittle2", "tittle3", "tittle4" };
char string[1000];
int k;
FILE *in_file = fopen("abce.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
while (1) {
printf("enter a array number that you want find in file: ");
fflush(stdout);
scanf("%d", &k);
if (k < 0)
break;
if (k >= (sizeof(word) / sizeof(word[0]))) {
printf("invalid index -- %d\n",k);
continue;
}
rewind(in_file);
int wordidx = 0;
while (1) {
if (fscanf(in_file, " %s", string) != 1)
break;
//printf("DEBUG: '%s'\n",string);
if (strcmp(string, word[k]) == 0) {
printf("we found the word '%s' in the file at offset %d\n",
word[k],wordidx);
break;
}
++wordidx;
}
}
return 0;
}
推荐阅读
- php - MySQL + PHP:避免由于连接表中的两个结果而导致重复结果
- git - 在我“压缩并合并”我的代码后,我的旧 git 用户名会保留为作者吗?
- security - 在 Jenkins 中存储密码参数的最佳方法是什么?
- python - 如何确保 python 脚本将在 Windows 上永远运行?
- wordpress - is there any multiple categories filter available in WordPress?
- ios - nil 在具有两个不同 Bundle 的两个 ViewController 之间进行委托(swift)
- node.js - 与集群 mongodb 相关的错误
- r - Creating unique time measurement ID for each user based on date of measurement (varying per user)
- c++ - C++ 中是否存在任何隐式内存屏障
- c# - 如何使用连接服务将自定义标头添加到传出 SOAP 有效负载?