4

I have two files: A and B. I need to replace B with A, while B is opened in another program.

The following approach:

MoveFile to rename B to C, then rename A to B, then delete C

works fine. However I need an atomic way to do that, because if one rename fails the data will be left in inconsistent state.

I tried MoveFileEx with MOVEFILE_REPLACE_EXISTING flag, but it doesn't work when file B is opened by another program. Same for ReplaceFile function. Any other ideas? Thank you

Isso
  • 1,285
  • 11
  • 23
  • This isn't an atomic operation, so could you possibly do it in an atomic way? Why can't you just use proper error handling? – Kyle C May 09 '13 at 21:32
  • File locks exist for a reason. Try the change, fail if it can't be done. – Pyrce May 09 '13 at 21:33
  • 3
    I suspect the answer is no way, try reading [this](http://stackoverflow.com/questions/167414/is-an-atomic-file-rename-with-overwrite-possible-on-windows) and see if it applies to you. – Stefano Sanfilippo May 09 '13 at 21:34
  • Error handling won't work. Let's say the file is on the network. First rename works, second fails, and the third (error handling) will also fail. So I'll leave the files in inconsistent state. Atomic operation is needed – Isso May 09 '13 at 21:40
  • @Kyle, atomic rename operation exists in Linux (of course, provided that the power supply is not abruptly interrupted, but there is the journal for handling that) and it's a totally legitimate request for any not-a-toy OS. – Stefano Sanfilippo May 09 '13 at 21:40
  • @Stefano: the OP is asking for a pair of renames as a single atomic operation. Does Linux really do that? – Harry Johnston May 10 '13 at 03:03
  • One possible solution is transactions, but that's a deprecated technology; in particular, it won't work on WinFS. It would probably be better to detect and repair these inconsistencies on the rare occasions when they occur. – Harry Johnston May 10 '13 at 03:09
  • @Harry why a pair? He needs to replace B with A. C is only auxiliary. – Stefano Sanfilippo May 10 '13 at 08:01
  • @StefanoSanfilippo: if he could delete B he wouldn't have a problem, since a move-and-replace is atomic. Since he can't, he wants to do a pair of renames as an atomic operation. Windows can actually do that in NTFS but not in WinFS, and the technology is considered deprecated. – Harry Johnston May 10 '13 at 10:45

0 Answers0