0

I have a function in c++ to write data to file:

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;
}

then I register that function

lua_register(L, "SaveFile", SaveFile);

and when I call

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

It successfully creates an empty file in the program directory and write data to it. Problem is I am using WinApi to create frames (also registered as lua functions), but when I use:

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

inside

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

function SaveFile is triggered, 'cout' tells me correctly which data were inserted to what file and then file is closed and reopened to read data in file again. All this seems to work perfectly, but no file is created in the program's directory..

Program is located on desktop. Lua code:

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)
greatwolf
  • 20,287
  • 13
  • 71
  • 105
Arko
  • 3
  • 2
  • 3
    Where is the program located? If it's in %ProgramFiles% etc, and UAC is active, then you probably don't have write permission. – Jonathan Potter Jan 19 '15 at 10:44
  • UAC is set to the lowest level possible and program is located on my desktop. – Arko Jan 19 '15 at 15:55
  • `'settings = {location = ''}'` that could create some confusion since you're embedding single quotes inside single quotes. You can use `"` but that would required escaping the string literal. You could use `[[]]` instead so no escaping is needed. – greatwolf Jan 19 '15 at 23:41
  • I am really dumb, thank you. :D – Arko Jan 22 '15 at 23:13

0 Answers0