简体   繁体   中英

C program doesn't output anything

This program is supposed to open a text file, then search for given words in 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. 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. 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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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