Detect file changes in windows and file changes in windows

Source: Internet
Author: User

Detect file changes in windows and file changes in windows

This mainly applies the script hot loading function mentioned in my previous blog. The main function is to detect changes (changes, additions, deletions, and renames) of files in the folder and notify lua to reload the script when any changes are found. Basically, it is the use of a windows api. In actual application, some details need to be noted. For example, I am used to sublime text editing, while sublime text saves a file instead of directly changing the file content, but adding a new file. These details need to be fine-tuned in actual use.

The Code is as follows:

# Include "FileWatcher. h "# include" cocos2d. h "# include" CCLuaEngine. h "using namespace cocos2d; # ifdef WIN32 // function: WatchChanges (LPVOID lpParameter) /// purpose: to monitor the program in the directory /// note: when the main function is created in the thread, the entry to this function is formulated // at that time, this subroutine will be automatically started for execution. // Note: Because the code is incomplete, refer to the red font section static int lastChangeTime = 0 when reading the following code; void reloadGame () {int time = GetTickCount (); if (time-lastChangeTime <= 1000) {// ignore the reload request return in a short period of time;} Director: getInstance ()-> getScheduler () -> extends mfunctionincosthread ([] () {auto engine = LuaEngine: getInstance (); ScriptEngineManager: getInstance ()-> setScriptEngine (engine ); lua_State * L = engine-> getLuaStack ()-> getLuaState (); lua_get Global (L, "reloadGame"); lua_call (L, 0, 0) ;});} dword winapi WatchChanges (LPVOID lpParameter) // return version information {wchar_t watchDirectory [512] = {0}; MultiByteToWideChar (CP_ACP, 0, (char *) lpParameter, strlen (char *) lpParameter), watchDirectory, sizeof (watchDirectory)/sizeof (wchar_t); // create a directory HANDLE handle_directory = CreateFile (watchDirectory, FILE_LIST_DIRECTORY, file_cmd_read | file_cmd_write | FILE_SHA RE_DELETE, NULL, OPEN_EXISTING, empty, NULL); if (handle_directory = INVALID_HANDLE_VALUE) {DWORD ERROR_DIR = GetLastError (); CCLOG ("Open Directory Error");} BOOL watch_state; while (TRUE) {char buffer [1024] = {0}; DWORD bytesReturned = 0; file_policy_information * policy = (file_policy_information *) buffer; watch_state = ReadDirectoryChangesW (handle_directory, (LPVOID) buffer, sizeof (buff Er), TRUE, file_policy_change_file_name | file_policy_change_dir_name | file_policy_change_last_write, (LPDWORD) & bytesReturned, NULL, NULL); int err = GetLastError (); if (err = ERROR_INVALID_FUNCTION | err = error_policy_enum_dir) {return-1;} if (watch_state! = 0) {DWORD length = WideCharToMultiByte (256, 1_y-> FileName,-1, NULL, 0, NULL, NULL); char fileName [] = {0 }; wideCharToMultiByte (0, 0, policy-> FileName,-1, fileName, length, NULL, NULL); // check the returned information. Pay attention to the definition of the file_policy_information struct, in order to call the returned information correctly, if (Policy-> Action = FILE_ACTION_ADDED) {CCLOG ("file add: % s", fileName); // The sublime file is a new temporary file, this is the compatibility measure reloadGame ();} if (Policy-> Action = FILE_ACTION_REMOVED) {CCLOG ("file delete: % s", fileName );} if (Policy-> Action = FILE_ACTION_MODIFIED) {CCLOG ("file changed: % s", fileName); reloadGame () ;}// for the following two cases, action itself is also the file name (either old_name or new_name) if (Policy-> Action = FILE_ACTION_RENAMED_OLD_NAME) {CCLOG ("file rename old name: % s", fileName );} if (Policy-> Action = FILE_ACTION_RENAMED_NEW_NAME) {CCLOG ("file rename new name: % s", fileName) ;}} Sleep (500);} return 0 ;} # endifvoid startWatch (const char * path) {# ifdef WIN32static std: string s_path = path; // create a thread dedicated to monitoring file changes HANDLE TrheadWatch = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) WatchChanges, (void *) s_path.c_str (), 0, NULL); CloseHandle (TrheadWatch); # endif}

Implementation registered to lua:

# Include "lua_cutil.h" // # include <conio. h> # include <stdlib. h> # include <ctype. h> # include <stdio. h> # include <string> # include "FileWatcher. h "# include <lua. h> # include <lauxlib. h> int lua_cutil_watch (lua_State * pL) {std: string path = luaL_checkstring (pL, 1); startWatch (path. c_str (); return 0;} int luaopen_cutil (lua_State * pL) {// register lua function luaL_Reg [] ={{ "watch", lua_cutil_watch}, {NULL, NULL }}; luaL_register (pL, "cutil", reg); return 1 ;}

Method called in lua:

                local mainPath = cc.FileUtils:getInstance():fullPathForFilename('Main.lua');                mainPath = string.sub(mainPath, 1, string.find(mainPath, 'Main%.lua') - 1);                print(mainPath);                cutil.watch(mainPath);


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.