简体   繁体   中英

comparing strings to certain pattern

#1

How can I check if the file is of a certain type?

I was trying to do it like this:

if(strcmp(filename, "*.txt") == 0){
    // do something
{

But unfortunately this doesn't work.


#2

I know that I can not use the * in strcmp. So how can I compare my string to a specific pattern?

For example:

if filename is ***.***.txt
do something

You could try this.

int len = strlen(filename);
if (len < 4) {
   printf("Filename too short\n");
   exit(1);
}
const char *extension = &filename[len-4];
if strcmp(extension, ".txt") == 0

You can search for the last occurrence of . with strrchr . If found, test against the exact string .txt :

ptr = strrchr (filename, '.');
if (ptr && strcmp(ptr, ".txt") == 0) {
    // do something

This won't even fail if the filename part of the full path does not contain an extension but the entire path does (then strcmp does not return 0 ), or there is no full stop at all in the entire path (then strrchr returns NULL ).

I prefer this method over manually counting the length of the extension, because it will work without adjusting with any length for the file extension.

Note that strcmp is strictly case sensitive. If your local library has either stricmp or strcasecmp , that may be a somewhat safer choice. ( stricmp is Microsoft-only, strcasecmp is the more standard Posix equivalent .)

I would use sscanf() . Something like this:

int length = 0;
sscanf( string, "%*[^ \n\r\t.].txt%n", &length );
if ( length >= 4 )
{
   do_something();
}

The list of white space characters is probably not complete but will probably work for you.

There's a function exactly for what you're asking for with no tricks. it's called fnmatch .

an example for usage:

int check_if_text( char *file_name ) 
{
    char *file_pattern = "*.txt";

    if ( fnmatch( file_pattern, file_name, 0 ) == 0 ) {
        return EXIT_SUCCESS;
    }
    return EXIT_FAILURE;
}

to use this function you will need to #include <fnmatch.h>

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