Question

Im working on a program in C that takes arguments as input. Is it possible to check if your argv contains a specific file extension? Like check if any char* in argv ends in .jpeg or something like that? (any example code would be greatly appreciated :) )

Was it helpful?

Solution

You can look for the last . with strrchr and then compare for the extension with strcmp

int found = 0;
char *p = strrchr(argv[1], '.');
if (p)
    found = strcmp(p, ".jpeg") == 0;

Alternatively, take the length of the extension off the end of the string and compare that

const char *ext = ".jpeg";
size_t xlen = strlen(ext);
size_t slen = strlen(argv[1]);
int found = strcmp(argv[1] + slen - xlen, ext) == 0;

This will also work in cases like .tar.gz.

OTHER TIPS

bool ends_with(char const *str, char const *suffix)
{
    size_t l0 = strlen(str);
    size_t l1 = strlen(suffix);

    if (l0 < l1)
        return false;

    return strcmp(str + l0 - l1, suffix) == 0;
}

int main(int argc, char *argv[])
{
    int i;

    for (i = 1; i < argc; ++i) {
        if (ends_with(argv[i], ".jpeg"))
            do_something();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top