Boardy
Boardy

Reputation: 36205

check if a string contains a string

I am currently working on a C program where I need to check whether there is a string inside a string. The string may be mylog.txt.1 and I want to check that it contains mylog.txt and if it does do something.

In order to perform this I am using the following code

int logMaintenance(void *arg)
{
    while (TRUE)
    {
        DIR *dir;
        struct dirent *ent;
        dir = opendir(directory);
        if (dir != NULL)
        {
            while ((ent = readdir (dir)) != NULL)
            {
                if (strstr(ent->d_name, fileName) != NULL )
                {
                    printf("%s\n", ent->d_name);
                }
            }
            closedir(dir);
        }
        else
        {
            printf("Failed to read directory %i", EXIT_FAILURE);
        }
        SL_WU_SleepUSecs(2000);
    }
    return 0;
}

However, this code doesn't seem to be working. For some reason it will just print mylog.txt and not include any of the other files that end in .1 or .2 etc. I've also tried using >=0 instead of != NULL in the if statement and this just prints everything even if it doesn't include mylog.txt.

Thanks for any help you can provide.

Upvotes: 0

Views: 1979

Answers (2)

Jens
Jens

Reputation: 72639

ANSI/ISO C provides the char *strstr(const char *haystack, const char *needle) function, allowing to find a needle in a haystack. Use #include <string.h> to get the prototype. Are you sure you have the args in the proper order?

Edit: I had the haystack and needle in the wrong order, blush.

Upvotes: 1

Ian Goldby
Ian Goldby

Reputation: 6174

You might have the parameters to strstr() the wrong way around. It's hard to tell from your description. Are you looking for fileName in ent->d_name, or the other way around?

The first is the string to search inside. The second is the string to search for.

Otherwise, try creating a test case with fixed data.

Upvotes: 0

Related Questions