[WinAPI] Cum deschid un folder?

Folosire Windows API in programe C/C++ (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3778
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[WinAPI] Cum deschid un folder?

Post by Ovidiu Cucu » 24 Nov 2009, 23:56

Problema: Pentru a deschide un fisier se foloseste functia CreateFile. In caz de succes, aceasta intoarce un handle care mai departe poate fi folosit in diverse alte functii de lucru cu fisiere.
Se poate folosi aceeasi functie pentru a deschide un director (folder)?

Raspuns: Da. Pentru a obtine un handle la un folder se foloseste functia CreateFile cu mentiunea ca trebuie sa-i pasam flag-ul FILE_FLAG_BACKUP_SEMANTICS.

Urmatorul exemplu deschide un folder si afiseaza data crearii.

Code: Select all

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

DWORD GetDirectoryCreationTime(LPCTSTR pszDir, FILETIME& ft)
{
   DWORD dwRet = NO_ERROR;
   HANDLE hFile = ::CreateFile(pszDir, 
                               GENERIC_READ, 
                               FILE_SHARE_READ|FILE_SHARE_WRITE,
                               NULL, 
                               OPEN_EXISTING, 
                               FILE_FLAG_BACKUP_SEMANTICS, // required if open a directory 
                               NULL);

   if(INVALID_HANDLE_VALUE == hFile)
   {
      dwRet = ::GetLastError();
   }
   else
   {
      if(!::GetFileTime(hFile, &ft, NULL, NULL))
      {
         dwRet = ::GetLastError();
      }
      ::CloseHandle(hFile);
   }
   return dwRet;
}

int main()
{
   FILETIME ft = {0};
   DWORD dwRet = GetDirectoryCreationTime(_T("c:\\tempxx"), ft);
   if(NO_ERROR != dwRet)
   {
      std::cout << "Error: " << dwRet << std::endl; 
      return dwRet;
   }

   SYSTEMTIME st = {0};
   ::FileTimeToSystemTime(&ft, &st);
   std::cout << "Creation time: " 
             << st.wDay << "." << st.wMonth << "." << st.wYear << " "
             << st.wHour << ":" << st.wMinute << ":" << st.wSecond << std::endl;
   return 0;
}
Vezi si
<< Back to Windows API Index



Post Reply