Comparing strings... (long but maybe worth it)

Andrew Koenig ark at alice.att.com
Tue Oct 16 00:39:27 AEST 1990


After seeing all the comments about comparing strings,
I couldn't resist adding yet another solution to the pile.

Here it is.  It's not completely portable, in that it depends
on the `popen' library function.  Some operating systems may
not have this particular function.  It also depends on certain
other characteristics of the host machine that should become
clear after you read it.

For the obvious reasons, I have not tested this program completely.


------------------------------------
#include <stdio.h>

extern FILE *popen(const char *, const char *);

void printhex(const char *, FILE *);

/*
 * This function compares two strings by sending their hex
 * representations to comp.lang.c and letting responses come
 * back to the user.
 */

void compare(const char *p, const char *q)
{
	FILE *fd = popen("EDITOR=ed postnews", "w");
	
	/* Is this message in response to some other message? */
	fprintf(fd, "n\n");

	/* Subject: */
	fprintf(fd, "string comparison request\n");

	/* Keywords: */
	fprintf(fd, "\n");

	/* Newsgroups (enter one at a time, end with a blank line): */

	/* The most relevant newsgroup should be the first, you should */
	/* add others only if your article really MUST be read by people */
	/* who choose not to read the appropriate group for your article. */
	/* But DO use multiple newsgroups rather than posting many times. */

	/* For a list of newsgroups, type ? */
	fprintf(fd, "comp.lang.c\n\n");

	/* Distribution (default='comp', '?' for help) : */
	fprintf(fd, "\n");

	/* We're now inside `ed'.  First explain the purpose of this */
	/* message, then call our hex function to print */
	/* each string in hex. */

	fprintf(fd, "Which of the following two strings is greater?\n");
	fprintf(fd, "Please answer by email and I will summarize for the net.\n");
	fprintf(fd, "\n");

	fprintf(fd, "String 1:\n");
	printhex(p, fd);
	fprintf(fd, "\n\nString 2:\n");
	printhex(q, fd);

	/* Now get out of ed */
	fprintf(fd, "\n.\nw\nq\n");

	/* What now?  [send, edit, list, quit, write] */
	fprintf(fd, "s\n");

	fclose(fd); sleep(2);
}

/* Print the string in hex, 32 chars (64 hex digits) to a line */
/* The first character, if any, is preceded by a newline. */
void printhex(const char *p, FILE* fd)
{
	unsigned count = 0;
	static char hextab[] = "0123456789abcdef";

	while (*p) {
		if (count % 32 == 0)
			putc('\n', fd);
		count++;
		putc(hextab[(*p & 0xf0) >> 4], fd);
		putc(hextab[*p & 0x0f], fd);
		p++;
	}
}
------------------------------------
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list