Comparing 2 strings to exclude based on extention
Ive had a look at this post: Find if string ends with another string in C++
I am trying to achieve a similar goal.
Basically i want to take a file list from a directory and filter out any files which do not end with a specified allowed extention for processing in my program.
In java this would be performed by creating a method and passing the extention accross as a string then using .endswith in th开发者_Go百科e following statement. C++ does not appear to support this so how would i go about it?
for (int fileList = 0; fileList < files.length; fileList++)
{
//output only jpg files, file list is still full
if(files[fileList].toString().endsWith(extension))
{
images.add(files[fileList]);
}//end if
}//end for
Thanks in advance
bool endsWith(std::string const & s, std::string const & e) {
if (s.size() < e.size())
return false;
return s.substr(s.size() - e.size()) == e;
}
If using boost::filesystem is ok for you then you could try
#include <boost/filesystem.hpp>
//...
boost::filesystem::path dir_path ("c:\\dir\\subdir\\data");
std::string extension(".jpg");
for (boost::filesystem::directory_iterator it_file(dir_path);
it_file != boost::filesystem::directory_iterator();
++it_file)
{
if ( boost::filesystem::is_regular_file(*it_file) &&
boost::filesystem::extension(*it_file) == extension)
{
// do your stuff
}
}
This will parse the given directory path and you then just have to filter desired extension.t
Next example checks if the filename ends with the jpg extension :
#include <iostream>
#include <string>
using namespace std;
bool EndsWithExtension (const string& str,const string &extension)
{
size_t found = str.find_last_of(".");
if ( string::npos != found )
{
return (extension == str.substr(found+1) );
}
return false;
}
int main ()
{
string filename1 ("c:\\windows\\winhelp.exe");
string filename2 ("c:\\windows\\other.jpg");
string filename3 ("c:\\windows\\winhelp.");
cout << boolalpha << EndsWithExtension(filename1,"jpg") << endl;
cout << boolalpha << EndsWithExtension(filename2,"jpg") << endl;
cout << boolalpha << EndsWithExtension(filename3,"jpg") << endl;
}
精彩评论