使用 std::ofstream 只能使用一次?
Using the std::ofstream only works once?
所以我在用 c++ 创建的这个函数时遇到了问题,似乎每当我调用记录器函数时,它只会向我写入的文件写入一次。第二次调用该函数将不会对其产生任何影响。我想确认这是否是 std::ofstream 的正确实现。所以总的来说,当我像下面这样调用 communicator::logger 的实例时:
main.cpp
communicator.logger("test1"); //A file called myLog.txt, inside has "test1" with a new line
communicator.logger("test2"); //This one won't show up.
communicator.cpp
void Communicator::logger(char *logData)
{
//Get the current time
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
//Get absolute path of the appdata/local directory
char* path = getenv("LOCALAPPDATA");
strcat(path, "\myApp\myLog.txt");
std::cout << path;
std::ofstream log(path, std::ios_base::app | std::ios_base::out);
log << buf << " " << logData << "\n";
}
你在危险的水域航行我的朋友
char* path = getenv("LOCALAPPDATA");
strcat(path, "\myApp\myLog.txt");
变量path
指向内部内存块,不能这样使用
你的程序在 strcat(path, "\myApp\myLog.txt");
中没有崩溃,这只是未定义行为的另一个例子。
尝试在使用前将其内容复制到另一个变量
std::string path = getenv("LOCALAPPDATA"); // beware getenv might return NULL
path += "\myApp\myLog.txt";
更新:
根据我的理解,有可能path的值最终是%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt
,第三次是%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt\myApp\myLog.txt
等等..
所以我在用 c++ 创建的这个函数时遇到了问题,似乎每当我调用记录器函数时,它只会向我写入的文件写入一次。第二次调用该函数将不会对其产生任何影响。我想确认这是否是 std::ofstream 的正确实现。所以总的来说,当我像下面这样调用 communicator::logger 的实例时:
main.cpp
communicator.logger("test1"); //A file called myLog.txt, inside has "test1" with a new line
communicator.logger("test2"); //This one won't show up.
communicator.cpp
void Communicator::logger(char *logData)
{
//Get the current time
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
//Get absolute path of the appdata/local directory
char* path = getenv("LOCALAPPDATA");
strcat(path, "\myApp\myLog.txt");
std::cout << path;
std::ofstream log(path, std::ios_base::app | std::ios_base::out);
log << buf << " " << logData << "\n";
}
你在危险的水域航行我的朋友
char* path = getenv("LOCALAPPDATA");
strcat(path, "\myApp\myLog.txt");
变量path
指向内部内存块,不能这样使用
你的程序在 strcat(path, "\myApp\myLog.txt");
中没有崩溃,这只是未定义行为的另一个例子。
尝试在使用前将其内容复制到另一个变量
std::string path = getenv("LOCALAPPDATA"); // beware getenv might return NULL
path += "\myApp\myLog.txt";
更新:
根据我的理解,有可能path的值最终是%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt
,第三次是%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt\myApp\myLog.txt
等等..