Get file name without extension?

I am new to the C ++ world, I ran into a very trivial problem, that is, getting the file name without the extension.

I have a TCHAR variable containing sample.txt and you only need to extract the sample , I used the PathFindFileName function, it just returns the same value as me.

I tried looking for a solution, but still no luck ?!

EDIT: I always get an extension with three letters, I added the following code, but in the end I get something like Montage (2)««þîþ , how can I avoid junk at the end?

 TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName) { int fileLength = _tcslen(fileName) - 4; TCHAR* value1 = new TCHAR; _tcsncpy(value1, fileName, fileLength); return value1; } 
+4
source share
5 answers

Here's how to do it.

 #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 std :: string or std :: wstring, depending on how UNICODE is set. To return to TCHAR *, you need to use StringType :: c_str (); This is a pointer to const, so you cannot change it, and it is not valid after the destruction of the string object.

+5
source

You can use the PathRemoveExtension function to remove the extension from the file name.

To get only the file name ( with extension ), you can first use PathStripPath followed by PathRemoveExtension .

+6
source

Try to find a solution,

 string fileName = "sample.txt"; size_t position = fileName.find("."); string extractName = (string::npos == position)? fileName : fileName.substr(0, position); 
+2
source
 TCHAR* FileHandler::GetFileNameWithoutExtension(TCHAR* fileName) { int fileLength = _tcslen(fileName) - 4; TCHAR* value1 = new TCHAR[fileLength+1]; _tcsncpy(value1, fileName, fileLength); return value1; } 
+2
source

Try the following:

Suppose 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 the letters in the original file name and add them one at a time to the new line of the file name.

There are several ways to do this, but this is one of the main ways to do this.

+1
source

All Articles