在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地址也是能夠的。運行結果:
網絡