gpt4 book ai didi

c++ - 如何在 Windows 上为调用用户获取桌面的绝对路径

转载 作者:行者123 更新时间:2023-11-30 05:23:39 36 4
gpt4 key购买 nike

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

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

最佳答案

编辑:如 Remy Lebeau 建议

I want to get absolute path to desktop for every computer starting program?

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

关于c++ - 如何在 Windows 上为调用用户获取桌面的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39055258/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com