c++ - 如何在软件代码中使用 ofstream 创建文件
问题描述
我正在开发一个软件,我的任务是对软件进行更改以添加我需要记录数据的某些功能。我正在尝试使用创建日志文件,ofstream
但我不知道为什么它没有在我的任何位置创建文件试过了。我有代码,我把它附加到现有的软件过程中。
ofstream k;
k.open("ko.txt",ios::app);
if (!k)
{
OutputDebugString(_T("file not created"));
return 1;
}
上面的代码总是打印未创建的文件。我已经尝试过%TMP%/orgName/Logs/ko.txt
无法创建日志文件的位置
解决方案
如果k.open("ko.txt",ios::app);
不起作用,则表示您无权在当前目录中创建文件或无法修改文件
在Windows下可以将文件创建到当前用户的Documents目录下,可以通过获取用户home目录getenv("USERPROFILE")
或者通过获取用户名getenv("USERNAME")
,目标是制作路径C:\\Users\<usename>\\Documents\\ko.txt
:
std::string path = std::string(getenv("USERPROFILE")) + "\\Documents\\ko.txt";
std::ofstream(path.c_str(), ios::app); // .c_str() useless since c++11
if (!k)
{
OutputDebugString(_T("file not created"));
return 1;
}
或者
std::string path = std::string(":\\Users\\") + getenv("USERNAME") + "\\Documents\\ko.txt";
std::ofstream(path.c_str(), ios::app); // .c_str() useless since c++11
if (!k)
{
OutputDebugString(_T("file not created"));
return 1;
}
推荐阅读
- python - 图像上沿折线/曲线的有序点列表
- android - MVVM:从内部片段更新 viewpager2 的容器视图
- javascript - 反应水平滚动标签在点击时跳跃?
- python - 为 pdf 下载启用 django 下载按钮
- python - 如何使用字符串作为指令
- excel - 如何循环用户窗体控件事件?
- javascript - 如何在 Google Chrome 扩展上获取活动标签索引?
- html - 如何检查变量是否小于ejs中的某个数字
- visual-studio - VS Code 在错误的路径中寻找图像
- kubernetes - Istio K8sObjectOverlay.PathValue 列表元素不起作用