Search code examples
macoscocoafile-ionsfilemanagernsfilewrapper

Check if two files are the same in Cocoa


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

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


Solution

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

    From the Docs:

    If path1 and path2 are directories, the contents are the list of files and subdirectories each contains—contents of subdirectories are also compared. For files, this method checks to see if they’re the same file, then compares their size, and finally compares their contents. This method does not traverse symbolic links, but compares the links themselves.