如何在软件代码中使用ofstream创建文件?

问题描述 投票:-1回答:1

我的工作是在一个软件上,我有一个任务,使软件的变化,以增加某些功能,我需要记录数据。ofstream 但我不知道为什么它不创建文件在任何位置,我试过了.我有代码,我把它附加到现有的软件过程。

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

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

c++ logging file-io ofstream
1个回答
0
投票

我想使用ofstream创建一个日志文件,但我不知道为什么它不能... k.open("ko.txt",ios::app); 不工作意味着你无权在当前目录下创建文件,或者你不能修改文件。

在Windows下,你可以将文件创建到目录下的 证件 当前用户的,你可以通过使用 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.