Link to home
Start Free TrialLog in
Avatar of Ingo Foerster
Ingo Foerster

asked on

remove last folder from path

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?
Avatar of jkr
jkr
Flag of Germany image

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

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.
}
Don't you think that deleting an entire directory is a bit overdoing it when it just should be removed from a string? ;o)
ASKER CERTIFIED SOLUTION
Avatar of sarabande
sarabande
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ingo Foerster
Ingo Foerster

ASKER

This works very well for me. Many thanks.