Reputation: 23
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.
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
Upvotes: 2
Views: 1179
Reputation: 22457
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.)
Upvotes: 2
Reputation: 974
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>
Upvotes: 0
Reputation: 6584
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.
Upvotes: 1
Reputation: 5773
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
Upvotes: 2