首页 > 解决方案 > 如何在软件代码中使用 ofstream 创建文件

问题描述

我正在开发一个软件,我的任务是对软件进行更改以添加我需要记录数据的某些功能。我正在尝试使用创建日志文件,ofstream但我不知道为什么它没有在我的任何位置创建文件试过了。我有代码,我把它附加到现有的软件过程中。

ofstream k;
k.open("ko.txt",ios::app);
if (!k)
    {
        OutputDebugString(_T("file not created"));
        return 1;
    }

上面的代码总是打印未创建的文件。我已经尝试过%TMP%/orgName/Logs/ko.txt 无法创建日志文件的位置

标签: c++loggingfile-ioofstream

解决方案


如果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;
}

推荐阅读