2016-08-20 288 views
1

如何爲啓動我的程序的用戶獲取桌面的絕對路徑?如何在Windows上爲主叫用戶獲取桌面的絕對路徑

int main() { 
    ofstream myfile; 
    myfile.open ("C:\\Users\\username\\Desktop\\example.txt"); 
    myfile << "Writing this to a file" << endl; 
    myfile.close(); 
} 
+0

將特定操作系統。如果你在Windows上,你可以[做這樣的事情](https://stackoverflow.com/questions/9542611/how-to-get-the-current-users-home-directory-in-windows) – CoryKramer

+0

@CoryKramer什麼你認爲「每臺電腦啓動程序」的含義是什麼? – nbro

+0

計算機上的每個用戶 – RedIcon

回答

1

編輯:作爲人頭馬勒博建議

我想絕對路徑桌面啓動程序的每一臺計算機?

如果你在Windows下你需要使用API​​ 的SHGetFolderPath功能,點擊here更多信息。

當你得到桌面的路徑時,你將需要將它與你的文件名相結合(附加),生成的路徑將代表位於桌面的文件的完整路徑,有完整的代碼:

#include <iostream> 
#include <Windows.h> 
#include <fstream> 
#include <shlobj.h> // Needed to use the SHGetFolderPath function. 

using namespace std; 

bool GetDesktopfilePath(PTCHAR filePath, PTCHAR fileName) 
{ 
    // Get the full path of the desktop : 
    if (FAILED(SHGetFolderPath(NULL, 
     CSIDL_DESKTOPDIRECTORY | CSIDL_FLAG_CREATE, 
     NULL, 
     SHGFP_TYPE_CURRENT, 
     filePath))) // Store the path of the desktop in filePath. 
     return false; 

    SIZE_T dsktPathSize = lstrlen(filePath); // Get the size of the desktope path. 
    SIZE_T fileNameSize = lstrlen(fileName); // Get the size of the file name. 

    // Appending the fileName to the filePath : 
    memcpy((filePath + dsktPathSize), fileName, (++fileNameSize * sizeof(WCHAR))); 

    return true; 
} 

int main() 
{ 
    ofstream myFile; 

    TCHAR filePath[MAX_PATH];    // To store the path of the file. 
    TCHAR fileName[] = L"\\Textfile.txt"; // The file name must begin with "\\". 

    GetDesktopfilePath(filePath, fileName); // Get the full path of the file situated in the desktop. 

    myFile.open(filePath);     // Opening the file from the generated path. 
    myFile << "Writing this to a file" << endl; 
    myFile.close(); 

    return 0; 
} 
+0

你爲什麼要手動掃描和複製緩衝區?由於您無論如何都使用Shell API,因此您應該使用['PathAppend()'](https://msdn.microsoft.com/en-us/library/windows/desktop/bb773565.aspx)或['PathCombine() '](https://msdn.microsoft.com/en-us/library/windows/desktop/bb77357..aspx)。我建議讓'GetDesktopfilePath()'返回一個'std :: string'而不是填充一個'char []'緩衝區。 –

+0

我是因爲很多原因而避免使用API​​,特別是當涉及到操縱字節時,無論如何,代碼對你有用? –

+0

無論如何,您正在使用Shell API,沒有理由避免使用其他Shell API函數,特別是在相同的函數中。否則,至少應該使用'lstrlen()','lstrcat()'等,而不是手動執行。 –

相關問題