IVIaximumPower
IVIaximumPower

Reputation: 131

Saving to %USERPROFILE%

So im trying to save my file to Documents on the C: Drive. So it allows me to give it someone else and it will save to their documents.

I read up on %USERPROFILE% which is meant to grab C:\Users\%USERPROFILE%\

ie mine would be C:\Users\jsmit\ but that doesn't work for me.

void savePassword(string stringpassword, string site) {
ofstream out("C:\\Users\\%USERPROFILE%\\Documents\\New folder\\output.txt", ofstream::app); // Here
out << site << ": " << stringpassword << endl; // This is where it saves the password into the text file
out.close(); // Closes file
}

It works if i do this:

ofstream out("C:\\Users\\jsmit\\Documents\\New folder\\output.txt", ofstream::app);

What code would i need to allow me to give it to someone else and it would be able to save to their documents by grabbing the correct file path?

Upvotes: 3

Views: 3523

Answers (3)

StackAttack
StackAttack

Reputation: 1219

This will get the user profile path on Windows or Linux with C++17 with filesystem.

example:

#include <filesystem>
#if defined(_WIN32)
#include <windows.h>
#include <shlobj.h>
#include <objbase.h>
// define a function that does it on windows
std::filesystem::path get_user_profile_path() {
  wchar_t *p;
  if (S_OK != SHGetKnownFolderPath(FOLDERID_Profile, 0, NULL, &p))
    return "";
  std::filesystem::path result = p;
  CoTaskMemFree(p);
  return result;
}
#elif defined(__linux__)
#include <cstdlib>
// function that does it on linux
std::filesystem::path get_user_profile_path() {
  std::cout << "getting linux user profile...\n\n\n";
  const char* p = getenv("HOME");
  std::filesystem::path result = p;
  return result;
}
#endif

// call our function
std::string our_user_profile_path = get_user_profile_path().string();

// test the path it recieved
#include <iostream>
std::cout << "Profile Path: " << our_user_profile_path << std::endl;

Additional Notes: If you don't have access to C++17, you can use the same filesystem commands with boost/filesystem.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180660

C++ knows nothing about your OS environment variables. If you want to get what that variable represents you can use std::getenv like

char * userpath = getenv("USERPROFILE");
std::string path
if (userpath != nullptr)
    path = std::string(userpath) + "\\Documents\\New folder\\output.txt";
else
    std::cout << "No user path";

Upvotes: 8

Some programmer dude
Some programmer dude

Reputation: 409196

The C++ standard library doesn't do any environment variable replacement, since it's an operating system specific thing.

It's up to you to do it with the help using e.g. GetEnvironmentVariable.

Upvotes: 1

Related Questions