Reputation: 1987
I have a writing process on C++ application, another C# application reads data continuously whenever the file has been changed.
On C++:
FILE *fp = fopen(result_file, "a");
if (fp) {
// Write some thing
fclose(fp);
}
On C#:
private void Init() {
FileSystemWatcher watcher = new FileSystemWatcher(ResultFolder);
watcher.Changed += new FileSystemEventHandler(OnResultChanged);
watcher.EnableRaisingEvents = true;
}
private void OnResultChanged(object sender, FileSystemEventArgs e) {
if (e.ChangeType == WatcherChangeTypes.Changed) {
// Check file ready to read
// Ready all lines
string[] lines = File.ReadAllLines(e.FullPath);
// Process lines
}
}
But sometimes the code on C++ cannot open the file to read, how can I fix it?
P/S: I found that on C# we have a way to share file access such as below command
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
But cannot find similar way in C++.
Upvotes: 0
Views: 753
Reputation: 283893
You're on Windows, so the C++ way is
CreateFile(.... FILE_SHARE_READ | FILE_SHARE_WRITE, ....)
It returns a Win32 HANDLE
, which is not the easiest thing to use in C++ (there are no convenience functions for formatted I/O). But you can turn it into a FILE*
or fstream
.
See this question:
Or, you can use the shflag
parameter of _fsopen()
or the _Prot
parameter of an fstream
constructor:
The argument shflag is a constant expression consisting of one of the following manifest constants, defined in Share.h.
Term Definition
_SH_COMPAT
Sets Compatibility mode for 16-bit applications.
_SH_DENYNO
Permits read and write access.
_SH_DENYRD
Denies read access to the file.
_SH_DENYRW
Denies read and write access to the file.
_SH_DENYWR
Denies write access to the file.
MSDN has the documentation and examples
Upvotes: 1