To find max palindrome in a given ascii text file

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>

void usage(char *s)
{
printf("Usage: %s <inputfile>\n", s);
exit(1);
}

int ispalindrome(const char *s)
{
const char *p = s + strlen(s) - 1;

while(s <= p)
{
if(*s++ != *p--) return 0;
}

return 1;
}

int main(int argc, char* argv[])
{
if(argc != 2)
usage(argv[0]);

int fd = open(argv[1], O_RDONLY);

if(fd == -1)
{
perror(argv[1]);
exit(1);
}

/* Buffer to hold data read from file */
char buf[64 * 1024];

/*Buffer to hold current word */
char str[4096];

/*Buffer to hold current max palindrome */
char palindrome[4096] = {0};
int maxlen = 0;

/* Temporay variables */
char *p = str;
int n;

while( (n = read(fd, buf, 64 * 1024)) > 0) /* Read 64k at a time */
{
int i = 0;

while(i < n) /* Divide into words */
{
if(isalpha(buf[i])) /*if alpha, Copy to temp buf*/
{
*p++ = buf[i];
}
else /* end of the word */
{
if( ((p - str) > maxlen) && ispalindrome(p) ) /* Check whether it is max palindrome */
{
*p = 0;
maxlen = p - str;
strcpy(palindrome, str);
}
p = str;
}
++i;
}
}

printf("%s %d\n", palindrome, maxlen);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s