Pra*_*dda 4 c++ filenames filehandle visual-c++
我是C++世界的新手,我遇到了一个非常微不足道的问题,即获取没有扩展名的文件名.
我有TCHAR变量包含sample.txt,只需要提取sample,我使用的PathFindFileName函数只返回我传递的相同值.
我试着谷歌搜索解决方案,但仍然没有运气?!
编辑:我总是得到三个字母的文件扩展名,我添加了以下代码,但最后我得到的东西,Montage (2)««þîþ如何最终避免垃圾字符?
TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName)
{
int fileLength = _tcslen(fileName) - 4;
TCHAR* value1 = new TCHAR;
_tcsncpy(value1, fileName, fileLength);
return value1;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用PathRemoveExtension函数从filename中删除扩展名.
要仅获取文件名(带扩展名),您可能首先使用PathStripPath,然后使用PathRemoveExtension.
这是它的完成方式.
#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);
}
Run Code Online (Sandbox Code Playgroud)
这将返回一个std :: string或std :: wstring,以适合UNICODE设置.要返回TCHAR*,您需要使用StringType :: c_str(); 这是一个const指针,因此您无法修改它,并且在生成它的字符串对象被销毁后它无效.
| 归档时间: |
|
| 查看次数: |
18515 次 |
| 最近记录: |