【问题标题】:How to get the absolute path of the desktop for the calling user on Windows如何在 Windows 上为调用用户获取桌面的绝对路径
【发布时间】:2016-08-20 14:34:07
【问题描述】:

如何为启动我的程序的用户获取桌面的绝对路径?

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

【问题讨论】:

  • 将是特定于操作系统的。如果你在 Windows 上,你可以do something like this
  • @CoryKramer 你认为“为每台计算机启动程序”是什么意思?
  • 计算机上的每个用户
  • @RedIcon 如果您指定您的解决方案是否必须仅在 Windows 或其他操作系统上运行,这一点很重要,因为在我看来,即使您只添加了 windows 的标签,也不清楚...
  • 你可能想要SHGetKnownFolderPath

标签: c++ windows file


【解决方案1】:

已编辑:正如 Remy Lebeau 建议的那样

我想为每台计算机启动程序获取桌面的绝对路径?

如果您在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;
}

【讨论】:

  • 为什么要手动扫描和复制缓冲区?由于无论如何您都在使用 Shell API,因此您应该改用 PathAppend()PathCombine()。我建议让GetDesktopfilePath() 返回std::string 而不是填充char[] 缓冲区。
  • 出于多种原因,我正在避免使用 API,尤其是在处理字节时,无论如何,代码对你有用吗?
  • 无论如何您都在使用 Shell API,没有充分的理由避免使用其他 Shell API 函数,尤其是在同一个函数中。否则,至少使用lstrlen()lstrcat() 等而不是手动操作。
  • 我按照您的建议对代码进行了一些更改,但函数的返回值是布尔值而不是字符串。
猜你喜欢
  • 1970-01-01
  • 2012-06-15
  • 2010-10-12
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
相关资源
最近更新 更多