Reputation: 139
Hello I'm trying to implement a way too check a file extension in a specific text file the code below doesn't seem to do what I want but I was wondering if this is somewhat the right direction to take in doing this. if not what library are there that would allow me to do this in as less code as possible.
string fn = ".txt";
if(fn.substr(fn.find_last_of(".") + 1) == ".txt") {
fprintf(stderr,"yes");
} else {
fprintf(stderr,"no");
}
im on windows 7 32bit
Upvotes: 0
Views: 4755
Reputation: 975
If you only need this to work on Windows, the best solution is to use the Win32 API PathMatchSpec.
For your example:
string fn = ".txt";
if(PathMatchSpecA(fn.c_str(), "*.txt") {
fprintf(stderr,"yes");
} else {
fprintf(stderr,"no");
}
Or as a function:
BOOL HasTxtFileExtension(LPCSTR filename)
{
return PathMatchSpecA(filename, "*.txt");
}
As would be expected, this function is case-insensitive and correctly handles the case where the directory contains dots but the file does not, e.g. C:\\directory.with.dots\\testtxt
.
Upvotes: 1
Reputation: 153899
My preferred solution would be boost::filesystem
, as minus suggests,
but if not:
static std::string const targetExtension( ".txt" );
if ( filename.size() >= targetExtension.size()
&& std::equal( filename.end() - targetExtension.size(),
filename.end(),
targetExtension.begin() ) ) {
std::cerr << "yes";
} else {
std::cerr << "no";
}
This would seem the simplest to me.
Upvotes: 2
Reputation: 706
I think boost filesystem library should help you (extension path function).
http://www.boost.org/doc/libs/release/libs/filesystem/index.html
Upvotes: 0
Reputation: 46027
fn.substr(fn.find_last_of(".") + 1)
returns "txt"
without the dot. So either remove +1
from substr
or compare with "txt"
without the dot.
Upvotes: 1