所以我的代码不工作...
test.c:27: warning: passing argument 1 of ‘search’ from incompatible pointer type
这是 fgets 行。
我的代码打开一个文件,逐行读取文件,我正在尝试创建一个“搜索”函数,该函数将返回一个值,该值指示是否在文件的那一行找到了该字符串。
我的最终目标是实现一个搜索替换程序。但是一步一步吧? 这是我到目前为止所拥有的:
#include <stdio.h>
#include <string.h>
int search(const char *content[], const char *search_term)
{
int t;
for(t=0; content[t]; ++t){
if(!strcmp(content[t], search_term)){
return t; // found
}
}
return 0; // not found
}
int main(int argc, char *argv[])
{
FILE *file;
char line[BUFSIZ];
int linenumber=0;
char term[20] = "hello world";
file = fopen(argv[1], "r");
if(file != NULL){
while(fgets(line, sizeof(line), file)){
if(search(line, term) != -1){
printf("Search Term Found!!\n");
}
++linenumber;
}
}
else{
perror(argv[1]);
}
fclose(file);
return 0;
}
最佳答案
改变
int search(const char *content[], const char *search_term)
到
int search(const char content[], const char *search_term)
编辑:
同时改变:
if(!strcmp(content[t], search_term)){
到
if(!strcmp(&content[t], search_term)){
或
if(!strcmp(content + t, search_term)){
由于您正在使用 strcmp
来查找匹配项,因此您将无法在文件中找到所有出现的搜索字符串。您只会在 search_string 中找到那些结束的行。
示例:您的搜索字符串是“hello world
”,假设文件有 2
行:
I wrote hello world
hello world is good
在这种情况下,您的程序将只能找到第 1 次出现,而不会找到第 2 次出现。
即使要找到此匹配项,您的代码也需要进行一些更改:
fgets
读取的字符串有一个尾随换行符,你必须像这样去掉它:
while(fgets(line, sizeof(line), file)){
line[strlen(line)-1] = 0;
此外,当搜索失败时,您将返回 0
,应将其更改为 -1
。
关于c - 在文件中搜索字符串 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2507909/