pmalek
6/12/2015 - 10:35 AM

Search for palindroms from one file and put it alphabetically in another

Search for palindroms from one file and put it alphabetically in another

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

int is_pal(char* word) {
    size_t len = strlen(word);
    char* begin = word;
    char* end = word + len - 2; // -2 beacuse we get the newline char as well
    if (len == 1) {
        return 1;
    }
    while (begin <= end) {
        if (*begin != *end) {
            return 0;
        }
        begin++;
        end--;
    }
    return 1;
}

/*
typedef struct node {
    char* data;
    struct node *next;
    } node;
*/

static int cmp(const void *p1, const void *p2){
    return strcmp(* (char * const *) p1, * (char * const *) p2);
}

int main(void)
{
  char* in = "pals.txt";
  char* out = "out_pals.txt";

  FILE* finput = fopen(in, "r");
  if (finput == NULL) {
      perror("fopen");
      exit(1);
  }
  FILE* foutput = fopen(out, "w");
  if (foutput == NULL) {
      perror("fopen");
      exit(1);
  }
    
  unsigned long num_of_palindroms = 0;
  unsigned long line_len = 0;
  char* line = NULL;
  // first pass
  while ( getline(&line, &line_len, finput) != -1) {
    if (is_pal(line)) ++num_of_palindroms;
  }
  printf("number of palindroms in %s: %d\n", in, num_of_palindroms);

  // ----------------------------------------
  char** palindrom_arr = malloc(sizeof(char*) * num_of_palindroms);

  //second pass
  unsigned int ii = 0;
  rewind(finput);
  while ( getline(&line, &line_len, finput) != -1) {
    if (is_pal(line))
    {
      palindrom_arr[ii] = malloc(sizeof(char) * line_len);
      strcpy(palindrom_arr[ii], line);
      ++ii;
    }
  }

  qsort(palindrom_arr, num_of_palindroms, sizeof(char *), cmp);

  int i = 0;
  for (;i  < num_of_palindroms; ++i) {
    fprintf(foutput, "%s", palindrom_arr[i]);
    free(palindrom_arr[i]);
  }
  free(palindrom_arr);

  free(line);
  fclose(finput);
  fclose(foutput);
  return 0;
}