Page 1 of 1

[WinAPI] Cum sterg, copii sau mut un folder?

Posted: 03 Aug 2007, 00:49
by Ovidiu Cucu
Problema
Functia RemoveDirectory da eroare daca folderul nu este gol iar cu functii precum CopyFile sau MoveFile nu se poate copia, respectiv muta decat un singur fisier.

Rezolvare (1)
O prima solutie ar fi sa folosim functiile FindFirstFile, FindNextFile si FindClose pentru gasi fisier cu fisier si a le sterge, copia, respectiv muta.

Rezolvare (2)
Prima solutie e destul de complicata dar exista una mult mai simpla si anume sa folosim functia SHFileOperation.

Exemple

Stergere folder:

Code: Select all

void DeleteFolder(LPCTSTR pszFolder)
{
   SHFILEOPSTRUCT fos = {0};

   fos.wFunc = FO_DELETE;
   fos.pFrom = pszFolder; 

   ::SHFileOperation(&fos); 
}
   // ...DeleteFolder(_T("c:\\temp\\test"));
Copiere folder:

Code: Select all

void CopyFolder(LPCTSTR pszFrom, LPCTSTR pszTo)
{
   SHFILEOPSTRUCT fos = {0};

   fos.wFunc = FO_COPY;
   fos.pFrom = pszFrom; 
   fos.pTo   = pszTo;

   ::SHFileOperation(&fos); 
}
   // ...
   CopyFolder(_T("c:\\temp"), _T("c:\\temp2"));
Mutare folder:

Code: Select all

void MoveFolder(LPCTSTR pszFrom, LPCTSTR pszTo)
{
   SHFILEOPSTRUCT fos = {0};

   fos.wFunc = FO_MOVE;
   fos.pFrom = pszFrom; 
   fos.pTo   = pszTo;

   ::SHFileOperation(&fos); 
}
   // ...
   MoveFolder(_T("c:\\temp"), _T("k:\\temp2"));
Nota: pentru a afla tot ce se poate face cu SHFileOperation, care este o functie destul de "flexibila", aruncati un ochi in documentatia structurii SHFILEOPSTRUCT.


<< Back to Windows API Index

Re: [WinAPI] Cum sterg, copii sau mut un folder?

Posted: 23 May 2008, 15:30
by Marius Bancila
Atunci cand se foloseste functia SHFileOperation trebuie avut grija ca fiecare path din sursa si destinatie sa fie null-terminater, iar string-ul sursa, respectiv destinatie, trebuie sa mai aiba un terminator la sfarsit. O functie, putin mai elaborata, de stergere a unui director poate arata asa:

Code: Select all

#include <windows.h>
#include <tchar.h>
#include <shellapi.h>

bool DeleteDirectory(LPCTSTR lpszDir, bool noRecycleBin = true)
{
  int len = _tcslen(lpszDir);
  TCHAR *pszFrom = new TCHAR[len+2];
  _tcscpy(pszFrom, lpszDir);
  pszFrom[len] = 0;
  pszFrom[len+1] = 0;
  
  SHFILEOPSTRUCT fileop;
  fileop.hwnd   = NULL;    // no status display
  fileop.wFunc  = FO_DELETE;  // delete operation
  fileop.pFrom  = pszFrom;  // source file name as double null terminated string
  fileop.pTo    = NULL;    // no destination needed
  fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user
  
  if(!noRecycleBin)
    fileop.fFlags |= FOF_ALLOWUNDO;

  fileop.fAnyOperationsAborted = FALSE;
  fileop.lpszProgressTitle     = NULL;
  fileop.hNameMappings         = NULL;

  int ret = SHFileOperation(&fileop);
  delete [] pszFrom;  
  return (ret == 0);
}

int main() 
{
  DeleteDirectory("d:\\Test", false);
  return 0;
}

<< Back to Windows API Index