【问题标题】:How to create file using ofstream in software's code如何在软件代码中使用 ofstream 创建文件
【发布时间】:2020-06-14 09:16:18
【问题描述】:

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

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

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

【问题讨论】:

  • 我在一些答案中找到它说要使用所以我使用了我不知道它是否有效:(
  • 是的,我明白我在问我在哪里可以在没有许可的情况下创建
  • 我正在使用 Windows。

标签: c++ logging file-io ofstream


【解决方案1】:

如果k.open("ko.txt",ios::app);不起作用,则表示您无权在当前目录下创建文件或无法修改文件

在Windows下可以将文件创建到当前用户的Documents目录下,可以通过getenv("USERPROFILE")获取用户home目录或者通过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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-13
    • 2017-10-27
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多