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;
}
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.