简体   繁体   English

C 程序没有 output 任何东西

[英]C program doesn't output anything

This program is supposed to open a text file, then search for given words in argv .该程序应该打开一个文本文件,然后在argv中搜索给定的单词。 It will search for the words line by line and if it finds one of the given words in that line the program should print it.它将逐行搜索单词,如果在该行中找到给定单词之一,程序应将其打印出来。

This the code I wrote for it:这是我为它写的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int existe_mot_cle(char s[1024], int argc, char *argv[])
{
    int test = 0;
    for (int i = 2; i < argc; i++)
    {
        if (strstr(s, argv[i]))
            test = 1;
        break;
    }
    return test;
}

int open_file(char *argv[], FILE *fp)
{
    fp = fopen(argv[1], "a");
}

int main(int argc, char *argv[])

{
    FILE *fp;
    char s[1024];

    if (!open_file(argv, fp))
        return 0;

    while (fgets(s, 1024, fp))
    {
        if (existe_mot_cle(s, argc, argv))
            printf("%s", s);
    }
    fclose(fp);
}

The problem is when I run it, nothing happens and I don't know why.问题是当我运行它时,什么也没有发生,我也不知道为什么。 I am new to the C language.我是 C 语言的新手。 Can someone give me the solution and explain it please?有人可以给我解决方案并解释一下吗?

You are break ing the for loop right after the first if statement is executed.您在执行第一个if语句后立即break for循环。 You should surround it with curly braces:你应该用花括号把它括起来:

int existe_mot_cle(char s[1024], int argc, char *argv[])
{
    int test = 0;
    for (int i = 2; i < argc; i++)
    {
        if (strstr(s, argv[i])) {
            test = 1;
            break;
        }
    }
    return test;
}

You can make it simpler and more generic:您可以使其更简单、更通用:

bool existe_mot_cle(char s[1024], size_t size, const char *ss[])
{
    for (size_t i = 0; i < size; i++) {
        if (strstr(s, ss[i]))
            return true;
    }
    return false;
}

Also, your open_file() should return an int , but it is not returning anything.此外,您的open_file()应该返回一个int ,但它没有返回任何东西。 Better remove it from your code since it serves no purpose:最好将其从您的代码中删除,因为它毫无用处:

int main(int argc, const char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s [file] [words]\n", argv[0]);
        return 0;
    }
    
    const char *filename = argv[1]; // More meaningful
    const char **otherarg = argv + 2;
    
    FILE *fp = fopen(filename, "r");
    
    if (!fp) {
        printf("Could not open %s.\n", filename);
        return 0;
    }
    
    char s[1024];
    while (fgets(s, sizeof s, fp))
    {
        if (existe_mot_cle(s, argc-2, otherarg)) // I'm using the second "simpler" version
            printf("%s", s);
    }
    
    fclose(fp);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM