StefanTflch
StefanTflch

Reputation: 143

How to get the absolute path of the desktop for the calling user on Windows

How can I get the absolute path to the desktop for the user that is starting my program?

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

Upvotes: 1

Views: 3447

Answers (1)

Amrane Abdelkader
Amrane Abdelkader

Reputation: 145

Edited : as Remy Lebeau suggested

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

If you are in windows you need to use the API SHGetFolderPath function, click here for more informations.

When you get the path of the desktop you will need to combine (append) it with your file name, the generated path will represents the full path of the file wich is situated in the desktop, there is the full code:

#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;
}

Upvotes: 1

Related Questions