Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file name without extension?

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;
}
like image 245
Prashant Cholachagudda Avatar asked Nov 30 '22 16:11

Prashant Cholachagudda


2 Answers

Here's how it's done.

#ifdef UNICODE //Test to see if we're using wchar_ts or not.
    typedef std::wstring StringType;
#else
    typedef std::string StringType;
#endif

StringType GetBaseFilename(const TCHAR *filename)
{
    StringType fName(filename);
    size_t pos = fName.rfind(T("."));
    if(pos == StringType::npos)  //No extension.
        return fName;

    if(pos == 0)    //. is at the front. Not an extension.
        return fName;

    return fName.substr(0, pos);
}

This returns a std::string or a std::wstring, as appropriate to the UNICODE setting. To get back to a TCHAR*, you need to use StringType::c_str(); This is a const pointer, so you can't modify it, and it is not valid after the string object that produced it is destroyed.

like image 180
Nicol Bolas Avatar answered Dec 05 '22 08:12

Nicol Bolas


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.

like image 34
Ajay Avatar answered Dec 05 '22 08:12

Ajay