Riddle me thisHard links & file moves
What would you expect the following code to output?
File.WriteAllText("a","1"); DirectoryBackup.CreateHardLink("b", "a", IntPtr.Zero); File.WriteAllText("a","2"); if(File.Exists("c")) File.Delete("c"); File.Move("b","c"); File.WriteAllText("a", "3"); Console.WriteLine(File.ReadAllText("c"));
CreateHardLink is:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
More posts in "Riddle me this" series:
- (12 Oct 2010) File access & Multi threading
- (06 May 2010) String outputs
- (02 May 2010) Hard links & file moves
Comments
3?
1?
2?
I'd expect 3. A hard link is just another name for the same file. Renaming only changes the name, so "a" and "c" still point to the same file.
Trying it out now... yes, returns 3 as expected.
I'd expect 3, but suspicious that it will not, since you're asking.
2 i think, because b is moved to c before teh "3" is written to a
I have to assume it will be "3".
When you create a hard link to a file, you have the filesystem create a new file node which will have it's own id, name, permissions, and whatever else is needed at that level. It then points to the same data nodes of the original file you linked it to.
A change in one will be reflected in the other regardless of the name of the files, since they have already be linked to the same data. Delete one and the data will still exists because there is still something linking to it. Symbolic links are a bit different since they are more like a redirect.
I agree with Copenhas, as long as no-one move a out of the way, c always has the same content as a.
They'll still have the same content if a is moved, since this is a hard link. As long as they're in the same drive.
To break the code and cause an exception: Have a directory called "c".
Comment preview