Check if two files match in Cocoa

How do you effectively check if two files are the same (have the same data) in Cocoa?

Context: I am writing a program that receives a file as input (input file) and copies it to a directory. If the directory already contains a file with the same name (namesake file), then the input file should be copied with the new name only if the namesake file is different.

+4
source share
2 answers

you can use -[NSFileManager contentsEqualAtPath:andPath:] .

From Documents:

If path1 and path2 are directories, the contents are also a list of files and subdirectories, each of which contains - the contents of the subdirectories are also compared. For files, this method checks if theyre support the same file, then compares their size and finally compares their contents. This method does not cross symbolic links, but compares the links themselves.

+5
source

While Justin answered my question, I used NSFileWrapper internally, so I could not always use contentsEqualAtPath:andPath:

In case this helps anyone, here is what I wrote to compare the contents of NSFileWrapper with the contents of the file:

 - (BOOL) contentsOfFileWrapper:(NSFileWrapper*)fileWrapper equalContentsAtPath:(NSString*)path { NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil]; NSUInteger fileSize = [attrs fileSize]; NSUInteger fileWrapperSize = [fileWrapper.fileAttributes fileSize]; // Will return zero if the file wrapper hasn't been written if (fileWrapperSize > 0 && fileSize != fileWrapperSize) return NO; NSData *fileData = [NSData dataWithContentsOfURL:fileURL]; NSData *fileWrapperData = fileWrapper.regularFileContents; return [fileData isEqualToData:resourceData]; } 

As Justin suggested, I only use this method if I cannot restore the path to the file shell. If I can, I use contentsEqualAtPath:andPath:

+2
source

All Articles