thegrinderguy
thegrinderguy

Reputation: 27

How to write to a file in use by another program in Windows?

I'm creating a program (doesn't really matter the objective but it happens to be purely to mess around and learn more about windows) which reads and writes to a file which is in use by another program (for example notepad or word).

Obviously I'm having trouble deleting it as I'm getting an access denied error because the file is in use.

My first idea was I should use CloseHandle (kernel32.dll) to close the handle to that file, but I have no clue how to find that handle in the first place.

Any ideas? I'm doing this in Rust, so if there are any language-specific suggestions that would be best but if not, that's more than fine too.

On another note, what would happen to the program after the handle has been closed? Would word or notepad still be able to edit it or would a subsequent save delete the changes made by my program or perhaps it wouldn't even save?

Upvotes: -1

Views: 276

Answers (1)

prog-fh
prog-fh

Reputation: 16925

This behaviour you observe is not related to Rust or to any other programming language, since this is system-specific. The CreateFileA() win32 call offers, thanks to its third parameter (dwShareMode), a means to explicitly specify how sharing could happen with the open file. Unfortunately (for you) this call is performed beforehand by the other program you try to hijack, not yours; your program cannot do anything, it's too late once the file is open.

Not that on UNIX the situation is different because the path to the file in the file-system is just a reference to the content of this file, as an open() operation is. Thus, if you remove (rm) the file indicated by this path, you just remove the reference (unlink()) but not its actual content if it is still referenced by an open file descriptor. The actual deletion of the file content only happens when no reference to it exists anymore.

Upvotes: 1

Related Questions