Writefile and readfile of Lua

Source: Internet
Author: User
Tags readfile
Lua readfile and writefile note: the string in Lua code can contain binary data string. len (STR) is not truncated by '\ 0'. When you pass data from Lua to C: You need to input the string containing binary data and the size of the data. The size is string. when Len (STR) is used to calculate the data transfer from C to Lua: lua_pushlstring instead of lua_pushstring, lua_pushstring internally uses strlen () to calculate the data length, while lua_pushlstring needs to input a sizeint luafilesystem :: readfile (lua_state * luastate) {If (! Lua_isstring (luastate, 2) {return 0;} const char * strpath = lual_checkstring (luastate, 2); STD: wstring wstrpath; transcode: utf8_to_unicode (strpath, strlen (strpath), wstrpath); handle hfile =: createfile (wstrpath. c_str (), generic_read, 0, null, open_existing, null, null); If (hfile! = Invalid_handle_value) {DWORD nfilesize =: getfilesize (hfile, null); char * lpbuffer = new char [nfilesize]; DWORD nnumberofbytesread; bool Bret =: readfile (hfile, lpbuffer, nfilesize, & nnumberofbytesread, null); lua_pushlstring (luastate, lpbuffer, nnumberofbytesread); Delete [] lpbuffer; closehandle (hfile); return 1;} return 0;} int luafilesystem :: writefile (lua_state * luastate) {If (! Lua_isstring (luastate, 2) |! Lua_isstring (luastate, 3) {return 0;} const char * strpath = lual_checkstring (luastate, 2); const char * strcontent = lual_checkstring (luastate, 3 ); int ncontentsize = strlen (strcontent); If (lua_isnumber (luastate, 4) {ncontentsize = lual_checkint (luastate, 4);} STD: wstring wstrpath; transcode :: utf8_to_unicode (strpath, strlen (strpath), wstrpath); handle hfile =: createfile (wstrpath. c_str (), g Eneric_write, 0, null, create_always, null, null); If (hfile! = Invalid_handle_value) {DWORD nnumberofbyteswritten;: writefile (hfile, strcontent, ncontentsize, & nnumberofbyteswritten, null); closehandle (hfile);} return 0 ;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.