tags:

views:

105

answers:

6

I have a filename (C:\folder\foo.txt) and I need to retrieve the folder name (C:\folder) in unmanaged C++. In C# I would do something like this:

string folder = new FileInfo("C:\folder\foo.txt").DirectoryName;

Is there a function that can be used in unmanaged C++ to extract the path from the filename?

+2  A: 

Example from http://www.cplusplus.com/reference/string/string/find_last_of/

// string::find_last_of
#include <iostream>
#include <string>
using namespace std;

void SplitFilename (const string& str)
{
  size_t found;
  cout << "Splitting: " << str << endl;
  found=str.find_last_of("/\\");
  cout << " folder: " << str.substr(0,found) << endl;
  cout << " file: " << str.substr(found+1) << endl;
}

int main ()
{
  string str1 ("/usr/bin/man");
  string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}
glowcoder
A: 

Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.

Cogwheel - Matthew Orlando
+2  A: 

Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.

Noah Roberts
+3  A: 

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();
AraK
+3  A: 

There is a standard Windows function for this:

http://msdn.microsoft.com/en-us/library/bb773748(VS.85).aspx

Andreas Rejbrand
Perfect, I was hoping there was a standard Windows way of doing this. Thanks!
Jon Tackabury
A: 

_splitpath is a nice CRT solution.

Ofek Shilon