0

我在 C++ 中有一个函数可以将数据写入文件:

static int SaveFile(lua_State *L)
{
  string file = lua_tostring(L,1);
  string data = lua_tostring(L,2);

  while(true)
  {
      string::size_type position = data.find ("\\");
      if (position == string::npos) break;
      else
          data.replace(position, 1, "/");
  }
  cout << data << endl;
  //myfile.clear();
  myfile.open (file.c_str(), ios::out);
  if (myfile.is_open())
  {
      myfile << data << endl;
      myfile.close();
  }
  else
    cout << "Error occured. #126 > Failed to read data from file: " << file << endl;

  cout << data << " should be saved to " << file.c_str() << endl;
  string data2;
  myfile2.open(file.c_str(), ios::in);
  string line;
  while (getline(myfile2, line))
  {
      data2 = data2 + line;
  }
  cout << data2 << " was read from the same file.." << endl;
  myfile2.close();
  myfile2.clear();
  return 0;
}

然后我注册该功能

lua_register(L, "SaveFile", SaveFile);

当我打电话时

luaL_dostring(L, "SaveFile('settings.lua', 'settings = {location = ''}')");

它成功地在程序目录中创建了一个空文件并将数据写入其中。问题是我正在使用 WinApi 创建框架(也注册为 lua 函数),但是当我使用时:

luaL_dostring(L, "SaveFile('settings.lua', 'settings = {location = ''}')");

里面

LRESULT CALLBACK WinProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)

函数 SaveFile 被触发,'cout' 正确地告诉我哪些数据被插入到哪个文件中,然后文件被关闭并重新打开以再次读取文件中的数据。所有这一切似乎都完美无缺,但程序目录中没有创建任何文件..

程序位于桌面上。卢阿代码:

SaveFile('settings.lua', 'settings = '..TableToString(settings)) -- no problem to write to a file
locateButton = CreateFrame("BUTTON")
locateButton:SetScript(function()
 settings.location=LocateFile("*.*");
 print(settings.location) -- prints correct address of selected file (c:/users/jan/desktop/settings.lua
 SaveFile('settings.lua', 'settings = '..TableToString(settings)) -- only prints data, but file is not created or overwritten
end)
4

0 回答 0