c - 在文件中搜索字符串 (C)

标签 c arrays pointers replace

所以我的代码不工作...

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/

相关文章:

ios - Mach-O 二进制 : external undefined symbols not found after patching symtab

c - travis CI 无法与 GitHub 上的 C 编译器配合使用?

有人可以解释我的内存池出了什么问题吗?

Java 我有一个无法跨类解析的数组

c - C 中可疑的指针到指针转换(面积太小)

c - 不在 cgo 中显示 printf 结果

arrays - Ruby:删除数组中重复值的所有实例

java - 如何在java android中排序后对json值求和?

c - malloc 返回类型转换困惑

c++ - 指针在退出递归函数后更改其地址