在windows下能够经过系统操做,将局域网的资源映射到本地,从而实现像本地数据同样访问网络资源。实际上这些步骤也可经过代码调用win32函数实现,前提是你得知道目标机器的地址以及密钥。windows
直接上VC的实例代码:api
#include <Windows.h> #include <iostream> #include <fstream> #pragma comment(lib, "mpr.lib") #pragma comment(lib, "Netapi32.lib") using namespace std; int main() { //在目标机器磁盘创建一个1.txt,没法直接读取 ifstream infile("\\\\Jishi\\D\\1.txt"); if (infile) { cout << "read txt!" << endl; } else { cout << "can't read txt!" << endl; } infile.close(); //创建网络磁盘映射的链接 string localName = "Y:"; string remoteName = "\\\\Jishi\\D"; string password = "123456"; string user = "administrator"; NETRESOURCE nr = { 0 }; nr.dwType = RESOURCETYPE_ANY; nr.lpLocalName = const_cast<char *>(localName.c_str()); nr.lpRemoteName = const_cast<char *>(remoteName.c_str()); nr.lpProvider = NULL; DWORD dRes = WNetAddConnection2(&nr, password.c_str(), user.c_str(), CONNECT_UPDATE_PROFILE); //经过GetLastError()检查错误代码 cout <<"链接结果:"<< dRes << endl; //读取映射盘符的链接 ifstream infile1("Y:\\1.txt"); if (infile1) { cout << "read txt!" << endl; } else { cout << "can't read txt!" << endl; } infile1.close(); //读取网络地址的链接 ifstream infile2("\\\\Jishi\\D\\1.txt"); if (infile2) { cout << "read txt!" << endl; } else { cout << "can't read txt!" << endl; } infile2.close(); //最后断开Y盘的链接 WNetCancelConnection("Y:", TRUE); return 0; }
该功能主要是经过调用WNetAddConnection2()函数来实现链接,经过WNetCancelConnection()函数断开的。其实链接后能够保证必定运行周期都是有效的,不用每次都断开从新再连。实际运用过程当中两个函数的返回值会提供错误信息,能够经过GetLastError()获取并检查。
这里访问了三次网络资源,链接前访问,链接后映射地址访问,网络地址访问。这里的网络地址改为IP地址也是能够的。运行结果:
网络