Get file name without extension?

2019-04-10 12:49发布

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

5条回答
家丑人穷心不美
2楼-- · 2019-04-10 13:09
TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName)
{
    int fileLength = _tcslen(fileName) - 4;
    TCHAR* value1 = new TCHAR[fileLength+1];
    _tcsncpy(value1, fileName, fileLength);
    return value1;
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-10 13:23

Try this:

Assuming the file name is in a string.

string fileName = your file.

string newFileName;

for (int count = 0;
   fileName[count] != '.';
   count++)
{
  newFileName.push_back(fileName[count]);
}

This will count up the letters in your original file name and add them one by one to the new file name string.

There are several ways to do this, but this is one basic way to do it.

查看更多
等我变得足够好
4楼-- · 2019-04-10 13:25

Try below solution,

string fileName = "sample.txt";
size_t position = fileName.find(".");
string extractName = (string::npos == position)? fileName : fileName.substr(0, position);
查看更多
唯我独甜
5楼-- · 2019-04-10 13:32

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.

查看更多
别忘想泡老子
6楼-- · 2019-04-10 13:32

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.

查看更多
登录 后发表回答