8

Suppose there is a CString variable which store the full path of the file.Now I hava to find only file name from if.How to do it in vc++.

CString FileName = "c:\Users\Acer\Desktop\FolderName\abc.dll"; 

Now I want only abc.dll.

2
  • you must escape your backslashes Commented Jul 17, 2012 at 12:22
  • I recommend the function decomposePath described here. Commented Feb 23, 2017 at 19:51

5 Answers 5

15

You can use PathFindFileName.

Remember that you have to escape the \ character in your path string!

Sign up to request clarification or add additional context in comments.

1 Comment

@Mark, Why to convert? If it is char* - ANSI build, pass char* !
14

Same as already stated above, but as u are using MFC framework, this would be the way to do it. Though this does not check files existence.

CString path= "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll"; CString fileName= path.Mid(path.ReverseFind('\\')+1); 

1 Comment

BTW CString is not just for MFC - see <atlstr.h>. More at msdn.microsoft.com/en-us/library/ms174288.aspx
7
std::string str = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll"; std::string res = str.substr( str.find_last_of("\\") + 1 ); 

Will get you "abs.dll".

1 Comment

Why use std::string when you have CString which has the required functions
2

I would use Boost::FileSystem for filename manipulation as it understands what the parts of a name would be. The function you want here would be filename()

If you are just getting the filename you can do this using CString functions. First find the ast backslash using ReverseFind and then Right to get the string wanted.

Comments

0

The code below demonstrate extracting a file name from a full path

#include <iostream> #include <cstdlib> #include <string> #include <algorithm> std::string get_file_name_from_full_path(const std::string& file_path) { std::string file_name; std::string::const_reverse_iterator it = std::find(file_path.rbegin(), file_path.rend(), '\\'); if (it != file_path.rend()) { file_name.assign(file_path.rbegin(), it); std::reverse(file_name.begin(), file_name.end()); return file_name; } else return file_name; } int main() { std::string file_path = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll"; std::cout << get_file_name_from_full_path(file_path) << std::endl; return EXIT_SUCCESS; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.