获取没有扩展名的文件名? [英] Get file name without extension?

查看:218
本文介绍了获取没有扩展名的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个非常微不足道的问题,即获取文件名,而不是扩展名。

我有 TCHAR包含 sample.txt 的变量,需要仅提取 sample c $ c> PathFindFileName 函数它只是返回相同的值,我传递。



我尝试googling解决方案,但仍没有运气? p>

编辑:我总是得到三个字母的文件扩展名,我添加了下面的代码,
但最后我得到像 Montage

  TCHAR * FileHandler:如何避免垃圾字符? :GetFileNameWithoutExtension(TCHAR * fileName)
{
int fileLength = _tcslen(fileName) - 4;
TCHAR * value1 = new TCHAR;
_tcsncpy(value1,fileName,fileLength);
return value1;
}


解决方案

/ p>

  #ifdef UNICODE //测试看看我们是否使用wchar_ts。 
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)//无扩展名。
return fName;

if(pos == 0)//。是在前面。不是扩展名。
return fName;

return fName.substr(0,pos);
}

这会返回一个std :: string或std :: wstring到UNICODE设置。要返回TCHAR *,需要使用StringType :: c_str();这是一个const指针,所以你不能修改它,并且在生成它的字符串对象被销毁后它是无效的。


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.

这篇关于获取没有扩展名的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆