Detect file changes under Windows

Source: Internet
Author: User

This is primarily the application of the Scripting Hot load feature mentioned in my previous blog post. The main implementation of the function detects changes in the file in the folder (change, add, delete, rename), notify Lua to reload the script when the change is found. is basically the use of a Windows API. The actual application will have some attention, such as I am accustomed to use sublime text editing, and sublime text save file is not directly change the contents of the file, but a new file. These details need to be fine-tuned in practical 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: Monitor the directory of the program////Comment: The main function creates a thread when the function is created in the Portal///Then the subroutine will automatically start execution. Note: Because the code is not complete, look at the following code when the main reference is the red font part of the static int lastchangetime = 0;void reloadgame () {int time = GetTickCount (); if (Time-la Stchangetime <= 1000) {//Ignore reload request in short time return;} Director::getinstance ()->getscheduler ()->performfunctionincocosthread ([] () {Auto engine = Luaengine:: GetInstance (); Scriptenginemanager::getinstance ()->setscriptengine (engine), lua_state* L = Engine->getluastack () Getluastate (); Lua_getglobal (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 handle_directory=createfile (watchdirectory, File_list_ DIRECTORY,  File_share_read | File_share_write | File_share_delete, NULL, open_existing, file_flag_backup_semantics, NULL); if (Handle_directory==invalid_handle_ VALUE) {DWORD error_dir=getlasterror ();  Cclog ("Open Directory Error");}  BOOL watch_state; while (TRUE) {char buffer[1024] = {0};D Word bytesreturned = 0; file_notify_information* NOTIFY = (file_notify_information*) buffer;watch_state=readdirectorychangesw (handle_ Directory, (LPVOID) buffer, sizeof (buffer), TRUE, file_notify_change_file_name| file_notify_change_dir_name| File_notify_change_last_write, (lpdword) &bytesreturned, NULL, NULL); int err = GetLastError (); if (err = = Error_ invalid_function | | Err = = Error_notify_enum_dir) {return-1;} if (watch_state! = 0) {DWORD length=widechartomultibyte (0,0,notify->  Filename,-1,null,0,null,null); Char filename[256] = {0};  WideCharToMultiByte (0,0,notify->filename,-1,filename,length,null,null); This is mainly to detect the returned information, you need to pay attention to the definition of file_notify_information structure, in order to correctly call the return information if (notify->action==file_action_added) {cclog ("File add:%s", fileName),//sublime Modify the file is a new temporary file, this is a compatible measure reloadgame ();}  if (notify->action==file_action_removed) {cclog ("FILE Delete:%s", fileName);}  if (notify->action==file_action_modified) {cclog ("FILE changed:%s", fileName); Reloadgame ();} For the following two cases, the Action itself is also a file name (possibly Old_name or new_name) if (notify->action==file_action_renamed_old_name) {Cclog (" File Rename old name:%s ", fileName);  } if (Notify->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 Trheadwa  Tch=createthread (null,0, (Lpthread_start_routine) watchchanges, (void*) s_path.c_str (), 0,null); CloseHandle (Trheadwatch); #endif}

The implementation that is 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 Reg [] = {{"Watch",     Lua_cutil_watch},{null, Null}};lual_ Register (PL, "Cutil", Reg); return 1;}

How to invoke 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);


Detect file changes under Windows

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.