节省%用户fofile%
Saving to %USERPROFILE%
所以我试图将我的文件保存到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
的相同文件系统命令。
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 当用户超过按钮点击限制时报告
- Visual C++(VS2017)中用户定义的转换不明确
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- RegGetValue在当前用户下找不到名称
- 节省%用户fofile%