C++ fstream opens a txt file in ios::out|ios::in mode, but Notepad can modify the file while the program is running. What's going on?
Note: For Win7 x64, the account is Administrator. There is no UAC, so it is directly the administrator.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[]) {
fstream file("test.txt",ios::in|ios::out);
file.open("test.txt",ios::in|ios::out);
char c;
cin>>c;
while(c!='X'){
cin>>c;
cout<<"Get a :"<<c<<endl;
}
return 0;
}
After clicking OK: the Save As dialog box will appear, and the result can be overwritten.
The program is still running, but the file has been modified.
Originally it could not be modified directly using sublimetext, but after some fiddling with Notepad, now sublimetext can also be modified.
Asking for advice, how can I prevent other programs from writing and deleting a certain file while the program is running, but can still read it.
Thank you.
我想大声告诉你2017-05-16 13:26:22
Let’s talk about your problem first: after Notepad overwrites the old file, the file opened by the process is the previous file (the previous file is still there, but you can’t see it), and the file you edit again is already a new file.
In Linux, even mandatory locks can be bypassed by unlinking, so there is no way to avoid this problem under Linux,
The system API under Windows should provide certain functions, but I know it very well, because I often find: "This file is occupied by a process and cannot be deleted", but I do not rule out bypassing this restriction
高洛峰2017-05-16 13:26:22
This question is quite interesting. The idea of troubleshooting can be as follows:
Is it a file IO cache problem?
Editor--System Buffer---Entity File
Is it a file read-write lock problem?
(I see that although your code opens the file in a readable and writable manner and establishes an association, it only uses reading; the read lock does not seem to be exclusive)