Re: Comparing two images
Re: Comparing two images
- Subject: Re: Comparing two images
- From: Alastair Houghton <email@hidden>
- Date: Fri, 28 Nov 2003 16:07:43 +0000
On 28 Nov 2003, at 15:44, Lorenzo wrote:
>
So let's consider the files are not images, but simple files, and I
>
would
>
like to compare them byte by byte. So I will consider equal only the
>
images
>
that have been duplicated by the Finder only.
Something like
#define BUFFER_SIZE 131072
...
NSFileHandle *fileA = [NSFileHandle fileHandleForReadingAtPath:@"File
A"];
NSFileHandle *fileB = [NSFileHandle fileHandleForReadingAtPath:@"File
B"];
BOOL filesDiffer = NO;
for (;;) {
NSData *dataA = [fileA readDataOfLength:BUFFER_SIZE];
NSData *dataB = [fileB readDataOfLength:BUFFER_SIZE];
/* If the data isn't equal, then the files differ */
if (![dataA isEqualTo
Data:dataB]) {
filesDiffer = YES;
break;
}
/* If there's no data, we're at the end of the file */
if (![dataA length])
break;
/* Flush the data, in case this is a big file */
[[dataA retain] release];
[[dataB retain] release];
}
should do the trick.
A similar example using BSD APIs instead might go something like the
following:
#include <fcntl.h>
#include <unistd.h>
...
#define BUFFER_SIZE 131072
...
void *buffer_a = malloc (BUFFER_SIZE);
void *buffer_b = malloc (BUFFER_SIZE);
int fd_a = open ("File A", O_RDONLY);
int fd_b = open ("File B", O_RDONLY);
bool files_differ = false;
/* Check the return values (omitted here for brevity) */
...
for (;;) {
ssize_t len_a = read (fd_a, buffer_a, BUFFER_SIZE);
ssize_t len_b = read (fd_b, buffer_b, BUFFER_SIZE);
/* Check for errors (omitted for brevity) */
...
/* If the data isn't equal, then the files differ */
if (len_a != len_b || memcmp (buffer_a, buffer_b, len_a)) {
files_differ = true;
break;
}
}
close (fd_a);
close (fd_b);
free (buffer_a);
free (buffer_b);
You might find that the BSD version runs faster because it doesn't keep
re-allocating its buffers. Aside from Carbon, which you have already
mentioned, there is another alternative, which is to use the C run-time
library's stdio functions (fopen(), fread() and fclose() rather than
open(), read() and close()); the C run-time library functions are
slightly more portable (if you're interested in coding for Windows as
well, for example), but won't be as fast as the BSD APIs for bulk data
manipulation.
Note also that whilst the error handling must be explicit in the BSD
version, the Cocoa version will throw exceptions. If the rest of your
program isn't set-up to handle them, then you need to make sure that
you wrap the code in an NS_DURING ... NS_HANDLER ... NS_ENDHANDLER
clause.
Kind regards,
Alastair.
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.