Get file name without extension?

Prashant Cholachagudda picture Prashant Cholachagudda · Jul 11, 2011 · Viewed 20.4k times · Source

I'm new to C++ world, I stuck with a very trivial problem i.e. to get file name without extension.

I have TCHAR variable containing sample.txt, and need to extract only sample, I used PathFindFileName function it just return same value what I passed.

I tried googling for solution but still no luck?!

EDIT: I always get three letter file extension, I have added the following code, but at the end I get something like Montage (2)««þîþ how do I avoid junk chars at the end?

TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName)
{
    int fileLength = _tcslen(fileName) - 4;
    TCHAR* value1 = new TCHAR;
    _tcsncpy(value1, fileName, fileLength);
    return value1;
}

Answer

Ajay picture Ajay · Jul 16, 2011

You can use PathRemoveExtension function to remove extension from filename.

To get only the file name (with extension), you may have first to use PathStripPath, followed by PathRemoveExtension.