0

A file name is being passed down into a function. The string needs to be checked to make sure it ends with ".bmp"

How do i check for that to later open the file?

For example: if a string contains "picture.txt" it will tell the user the string is not in the correct format. If a string contain "picture.bmp" it should accept it for later use of opening the file.

Thanks in advance!

user3249979
  • 21
  • 1
  • 5

2 Answers2

1

What OS are you using? If it's Windows / Visual C++, you have functions that properly give you the extension given a file name (for example _spiitpath). If you want something portable, you have boost::filesystem to parse out the name.

The reason why you should use these functions instead of trying to cook something up yourself is that there could be corner or edge cases that you didn't consider, thus causing your code to give wrong results.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
  • Then the cross-platform boost::filesystem::extension() function will return the extension. See here: http://www.boost.org/doc/libs/1_55_0/libs/filesystem/doc/reference.html – PaulMcKenzie Mar 09 '14 at 04:30
0

You can do something like this:

bool hasExtension(const string& filename, const string& extension)
{
  size_t fnlen = filename.length();
  size_t exlen = extension.length();
  if (fnlen < exlen)
     return false;

  return memcmp(filename.c_str() + fnlen - exlen, extension.c_str(), exlen) == 0;
}


int main()
{
  cout << hasExtension("file.txt", ".txt") << endl;
}
ebasconp
  • 1,608
  • 2
  • 17
  • 27
  • I don't understand what is being returned with the "return filext == extension;" – user3249979 Mar 09 '14 at 04:26
  • Could you please explain? – user3249979 Mar 09 '14 at 04:27
  • I was getting the extension of the filename passed as argument and comparing such extension with the extension passed as argument. Since the algorithm was kind of slow because I was getting a substring, I replaced that by a memcmp call. – ebasconp Mar 09 '14 at 04:32