/**************************************************
  Text Trim -- Reduce multiple empty lines in
  text files to single empty line.
  Nov 2000, Allen Lam
**************************************************/

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

char fin[30], fout[30];

/*test whether file exist*/
int fexist(char *fname){
  FILE *fp;
  fp = fopen(fname, "r");
  if (fp == NULL) return 0;  //not exist
  else {fclose(fp); return 1;} //exist
}

int getname(){
  puts("\n*** Trim Text v1.0 by Allen Lam ***\n");
  printf("Input filename:  ");
  scanf(" %s", fin);
  if (!fexist(fin)) return 1;

  printf("Output filename: ");
  scanf(" %s", fout);
  if (fexist(fout)) return 2;

  return 0;
}

/*cut ending spaces*/
void trimln(char *ln){
  int i;
  for (i=strlen(ln)-1; i>=0; i--){
    if (isspace(ln[i])) ln[i] = '\0'; else break;
  }
  strcat(ln, "\n");
}

/*reduce multiple empty lines into single empty lines*/
int trimtxt(){
  FILE *fp1, *fp2;
  char ln[256];
  int count = 0;

  fp1 = fopen(fin, "r");
  fp2 = fopen(fout, "w");

  while (fgets(ln, 256, fp1)!=NULL){
    trimln(ln);
    if (strcmp(ln, "\n") != 0){    //if ln is not empty
      fputs(ln, fp2);
      count = 0;
    } else
    {                              //if ln is empty string
      count++;
      if (count <= 1) fputs(ln, fp2);
    }
  }

  if (fclose(fp1) != 0) return 1;  //if error in closing input
  if (fclose(fp2) != 0) return 1;  //if error in saving output

  return 0;
}

int main(){
  char ch = 0;
  int err;

  err = getname();
  if (err == 1){
    puts("\nInput file does not exists.");
    fflush(stdin); getchar();
    return 1;
  }

  if (err == 2){
    do{
    printf("Output file already exists. It will be overwritten. Continue? (Y/N) ");
    fflush(stdin);
    ch = toupper(getc(stdin));
    } while ((ch!='Y')&&(ch!='N'));
    if (ch == 'N') return 2;
  }

  if (trimtxt() == 0)
    puts("\nFile is trimmed and saved."); else
    puts("\nCannot save output file.");

  fflush(stdin); getchar();
  return 0;
}

back