开发者

Get file name without extension?

开发者 https://www.devze.com 2023-03-19 02:24 出处:网络
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 PathFindFileNa

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 s开发者_StackOverflow中文版olution 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.


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.


Try below solution,

string fileName = "sample.txt";
size_t position = fileName.find(".");
string extractName = (string::npos == position)? fileName : fileName.substr(0, position);


TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName)
{
    int fileLength = _tcslen(fileName) - 4;
    TCHAR* value1 = new TCHAR[fileLength+1];
    _tcsncpy(value1, fileName, fileLength);
    return value1;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号