0

I need to get the extension from filename and compare it to my array of extensions. But looks like TCHAR do not have strpos()-like function, so I am walking an array of TCHAR (not the best solution?) to search for the '.' sign and extract a file extension. But it doesn't work.

for (int i = 0; i < extCount; i++)
{
    //wsprintf(fileName, L"%d", extCount);
    //_tcscpy_s(fileName, extensions[i]);

    _tcscpy_s(fileName, fileData.cFileName);

    for (int k = wcslen(fileName); k >= 0; k--)
    {
        if (fileName[k] == (LPCWSTR)TCHAR('.'))
        {
            wsprintf(temp, L"%c", fileName[k]);
            MessageBox(NULL, fileName[k], L"Файл", MB_OK);
        }
    }

So the problem is, how to get and compare the file extension in simpliest and most effective way? And other question is - should I really use TCHAR? Because there is so much trouble with this type. When do they used on practice?

Niall
  • 30,036
  • 10
  • 99
  • 142
Ivan Petrov
  • 155
  • 2
  • 18

3 Answers3

5

You can use the PathFindExtension Windows API function (since you're obviously coding for Windows from your posted code). This is in shlwapi.dll so you'll need to #include <shlwapi.h> and link your project with shlwapi.lib.

It returns a pointer to the '.' at the beginning of the file extension, so you can just pass this pointer to a string comparison function like _wcsicmp to compare it.

By the way, TCHAR is a macro that expands to either char or wchar_t depending on whether your project is built for ANSI or Unicode. It's not a class and doesn't have methods, a TCHAR array is just an array of characters.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
3
  1. There is TCHAR version of such function: tcsstr;
  2. TCHAR is pretty outdated thing, use char/wchar_t, or even better - std::string/std::wstring instead;
  3. File name could contain many . symbols, so using string search routines seems like an overkill. Simply locate last point in your string and increment string pointer to its index. You will obtain substring with the file extension.
Ari0nhh
  • 5,720
  • 3
  • 28
  • 33
2
std::wstring GetLastExtension(const std::wstring &fileName)
{
    auto pos = fileName.rfind(L".");
    if (pos == std::wstring::npos)
        pos = -1;
    return std::wstring(fileName.begin() + pos, fileName.end());
}

Or use the Windows API PathFindExtension.

How to compare - std::wstring::compare

See this about using TCHAR.
Short: Do not use it.

Community
  • 1
  • 1
Blacktempel
  • 3,935
  • 3
  • 29
  • 53