remove last folder from path

Ingo Foerster
Ingo Foerster used Ask the Experts™
on
Hello,
I have a Cstring with file path information. As sample: C:\ProrgamData\MyFolder\Logs\
How can I remove the last folder "Logs" from this path?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
jkr
Top Expert 2012

Commented:
Windows has the Shell Helper API that can help you with that, All you need to do is calling 'PathAppend()' () and add a ".." to go up one direectory, e.g. like

#include <windows.h>
#include <iostream>
#include "Shlwapi.h"
#include <tchar.h>

#pragma comment(lib,"shlwapi.lib")

using namespace std;

void main( void )
{

  TCHAR acOrig[MAX_PATH] = _T("C:\\ProrgamData\\MyFolder\\Logs\\");

  cout << acOrig << endl;

  PathAppend(acOrig,_T("..")); // go up one directory

  cout << acOrig << endl;
}

  

Open in new window

jkr
Top Expert 2012

Commented:
BTW, which version is Visua C++ are you using? That's because the handling of CStrings differs slightly between them, so in order to show you how to use them with the above, I have to ask...
You can use SHFileOperation() to remove a directory. Search msdn for it's supported OS.

code:

// @param: dir - Fully qualified name of the directory being   deleted,   without trailing //backslash

int silently_remove_directory(LPCTSTR dir) {
 
int len = strlen(dir) + 2; // required to set 2 nulls at end of argument to SHFileOperation.
  char* tempdir = (char*) malloc(len);
  memset(tempdir,0,len);
  strcpy(tempdir,dir);

  SHFILEOPSTRUCT file_op = {
    NULL,
    FO_DELETE,
    tempdir,
    "",
    FOF_NOCONFIRMATION |
    FOF_NOERRORUI |
    FOF_SILENT,
    false,
    0,
    "" };
  int ret = SHFileOperation(&file_op);
  free(tempdir);
  return ret; // returns 0 on success, non zero on failure.
}
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

jkr
Top Expert 2012

Commented:
Don't you think that deleting an entire directory is a bit overdoing it when it just should be removed from a string? ;o)
Top Expert 2016
Commented:
you could do it by

CString strPath = _T("C:\\ProgramData\\MyFolder\\Logs\\");
strPath.Trim();
int len = strPath.GetLength();
int pos;

while ((pos = strPath.ReverseFind(_T('\\'))) >= 0)
{
     strPath = strPath.Left(pos);
     // we skip one trailing backslash
     if (pos == len-1)
     {
           continue;
     }
     break;
}

Open in new window


note, the resulting path hasn't a backslash at end.

Sara
Ingo FoersterOwner, CTO

Author

Commented:
This works very well for me. Many thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial