window API一天一练习之磁盘遍历

来源:互联网 发布:java培训班出来的人 编辑:程序博客网 时间:2024/05/22 03:49

   获取主机上驱动器的两种方法:一是用GetLogicalDrives,或者GetLogicalDrives。二是用FindFirstVolume和FindNextVolume。

GetLogicalDrives

DWORD WINAPI GetLogicalDrives(void);
该函数没有参数,返回值为DWORD,是一个位掩码代表当前的磁盘驱动器。第0位表示驱动器A,第二位表示驱动器B。以此类推,某一位为1表示存在驱动器,为0表示不存在。

void GetDisksInformation(){printf("Begin Call GetDisksInformation()\n");DWORD dwDisk = GetLogicalDrives();int dwMask = 1;int step = 1;dwMask<<1;while (step < 32){++step;switch (dwMask&dwDisk){case 1:printf("volume  A\n");break;case 2:printf("volume  B\n");break;case 4:printf("volume  C\n");break;case 8:printf("volume  D\n");break;case 32:printf("volume  E\n");break;case 64:printf("volume  F\n");break;case 128:printf("volume  G\n");break;case 256:printf("volume  H\n");break;default:break;}dwMask = dwMask<<1;}printf("end Call GetDisksInformation()\n");}



GetLogicalDriveStrings

DWORD WINAPI GetLogicalDriveStrings(  _In_   DWORD nBufferLength,  _Out_  LPTSTR lpBuffer);
lpBuffer ,存储驱动器根路径字符串的缓冲区内存
nBufferLength 缓冲区 的大小

void GetDisksInformationEx(){printf("Begin Call GetDisksInformationEx()\n");CHAR szLogicalDriveString[BUFFERSIZE];PCHAR szDrive;ZeroMemory(szLogicalDriveString,BUFFERSIZE);GetLogicalDriveStrings(BUFFERSIZE - 1, szLogicalDriveString);szDrive = szLogicalDriveString;while (*szDrive){printf("volume %s\n",szDrive);szDrive += (lstrlen(szDrive) + 1);}printf("end Call GetDisksInformationEx()\n");}




FindFirstVolume


HANDLE WINAPI FindFirstVolume(  _Out_  LPTSTR lpszVolumeName,      //驱动器名的缓冲区  _In_   DWORD cchBufferLength       //缓冲区的大小);
返回值为驱动器的句柄
该函数用来查找主机上第一个驱动器,返回驱动器名。

BOOL WINAPI FindNextVolume(  _In_   HANDLE hFindVolume,    //调用FindFirstVolume返回的驱动器句柄  _Out_  LPTSTR lpszVolumeName, //驱动器名的缓冲区  _In_   DWORD cchBufferLength  //缓冲区的大小);
查找下一个驱动器

BOOL WINAPI FindVolumeClose(  _In_  HANDLE hFindVolume   //调用FindFirstVolume返回的驱动器句柄);
该函数用来关闭一个驱动器的句柄。被关闭的句柄就不能再在FindNextVolume或者FindVolumeClose中使用了。

void FindVolume(){printf("Begin Call FindVolume()\n");CHAR  szVolume[MAX_PATH];HANDLE hVolume;ZeroMemory(szVolume,MAX_PATH);hVolume = FindFirstVolume(szVolume,MAX_PATH);if (hVolume == INVALID_HANDLE_VALUE){printf("Not found the first volume\n");}printf("volume  %s\n",szVolume);while (FindNextVolume(hVolume,szVolume,MAX_PATH)){printf("volume  %s\n",szVolume);}FindVolumeClose(hVolume);printf("end Call FindVolume()\n");}




原创粉丝点击