How to track text file changes using C ++? Difficulty: no.

Use case: a third-party application wants to programmatically control a text file created by another program. The text file contains the data that you want to analyze as it is updated.

I find many answers to this question wrapped around FileSystemWatcher, but let me say that you are writing an application for a Windows machine and cannot guarantee that .NET is installed.

Are there any libraries for this, or will I just need to roll up my own solution?

Thanks.

+4
source share
4 answers

You can control the directory with FindFirstChangeNotification works in any windows.
This is useful if you know where the file is located. Otherwise, you can use the virtual / Filemon driver described below to check for changes anywhere in the system.

Sample code here

+8
source

A simpler solution would be to check the last modified timestamp of the file.

If you use the _stat64 () function to do this, it becomes a cross-platform solution.

Code example:

struct __stat64 fileinfo; if(-1 != _stat64(filename, &fileinfo) return fileinfo.st_mtime; 
+5
source
+1
source

This is very similar to that of FileMon, from sysinternals (now MS). They do this by creating a dynamic virtual device driver. they have a good description of how this works here :

How FileMon Works

For the Windows 9x driver, the heart of FileMon is in the virtual device driver, Filevxd.vxd. It loads dynamically, and when it is initialized, it sets the file system filter through VxD, IFSMGR_InstallFileSystemApiHook, to insert itself into the call chain all file system requests. On Windows NT, the heart of FileMon is a system driver file that creates and attaches filter device objects to file system device targets, so FileMon will see all IRP and FastIO Requests directed to disks. When FileMon sees an open, making or closing a call, it updates the internal hash table, which serves as a mapping between the internal files and the file path names. Whenever he sees calls that are based on a descriptor, he looks at the process in the hash table to get the full name to display. If link-based access refers to a file open before starting FileMon, FileMon will not be able to find the display in its hash table and will simply present a value instead.

+1
source