使用 std::ofstream 只能工作一次



所以我在 c++ 中创建的这个函数时遇到了问题,似乎每当我调用记录器函数时,它只会写入一次我写入的文件。对该函数的第二次调用将对其产生任何影响。我想确认这是否是std::ofstream的正确实现。所以总的来说,当我调用 communicator::logger 的实例时,如下所示:

主.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.

沟通者.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";

更新:据我了解,路径的价值有可能最终是%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt,第三次%LOCALAPPDATA%\myApp\myLog.txt\myApp\myLog.txt\myApp\myLog.txt等等。

最新更新