问题描述
是否有一种简单的方法来获取c ++中所有打开的命名管道,就像c#中那样?
String[] listofPipes = System.IO.Directory.GetFiles(@"\\.\pipe\");
我发现了这个article,其中提出了获取所有打开的命名管道的不同方法,不幸的是,对于c ++ c0x来说什么都不是。
解决方法
由于不能使用C ++ 17,因此需要WinAPI遍历目录的方式。就是FindFirstFile
/ FindNextFile
。尽管有名称,但如果您查看\\.\pipe\
,也会找到管道。
.NET的许多源代码可在https://referencesource.microsoft.com上公开获得。
如果您查看source code类的System.IO.Directory
,则其GetFiles()
方法使用FileSystemEnumerableFactory.CreateFileNameIterator()
中的TList<String>
创建一个IEnumerable<String>
,然后将该TList<String>
转换为String[]
数组,其中FileSystemEnumerableIterator
在内部使用Win32 API FindFirstFile()
和FindNextFile()
函数。
因此,声明:
String[] listOfPipes = System.IO.Directory.GetFiles(@"\\.\pipe\");
直接使用Win32 API将大致等同于以下C ++代码:
#include <windows.h>
#include <string>
#include <vector>
std::vector<std::wstring> listOfPipes;
std::wstring prefix(L"\\\\.\\pipe\\");
WIN32_FIND_DATAW fd;
HANDLE hFind = FindFirstFileW((prefix + L"*").c_str(),&fd);
if (hFind == INVALID_HANDLE_VALUE)
{
// error handling...
}
else
{
do
{
listOfPipes.push_back(prefix + fd.cFileName);
}
while (FindNextFileW(hFind,&fd));
// error handling...
FindClose(hFind);
}