节省%用户fofile%

Saving to %USERPROFILE%

本文关键字:fofile% 用户 节省      更新时间:2023-10-16

所以我试图将我的文件保存到c:drive上的文档。因此,它使我能够给别人,并将其保存到他们的文档中。

我在%userProfile%上读取,该%旨在获取C: users %userProfile%

ie我的是c: users jsmit ,但这对我不起作用。

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
}

如果我这样做:

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

我需要允许我将其提供给其他人,并且可以通过抓取正确的文件路径来保存其文档?

c 对您的OS环境变量一无所知。如果要获得该变量代表的内容,则可以使用 std::getenv,例如

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";

C 标准库不执行任何环境变量替换,因为它是操作系统的特定内容。

通过使用例如使用例如GetEnvironmentVariable

这将在Windows或Linux上使用Filesystem获得Windows或Linux上的用户配置文件路径。

示例:

#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...nnn";
  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;

附加说明:如果您无法访问C 17,则可以使用boost/filesystem的相同文件系统命令。