我在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被触发,&#39; cout&#39;正确地告诉我哪些数据被插入到哪个文件然后文件被关闭并重新打开以再次读取文件中的数据。所有这些似乎都很完美,但是在程序的目录中没有创建文件..
程序位于桌面上。 Lua代码:
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)