Concatenate by command line argument

Posted: February 9, 2012 in OOP344

Basic Code without error message and safe guard.

#include <cstdio>

int concat(char* file1, char* file2) {
  FILE* fp1 = fopen(file1, "a");
  FILE* fp2 = fopen(file2, "r");
  char ch;
  int status = 0;
  if (fp2 && fp1) {
    for(;(ch=fgetc(fp2)) != EOF; fputc(ch, fp1));
    fclose(fp2);
    fclose(fp1);
    status = 1;
  }
  return status;
}

int main(int argc, char** argv) {
  int i=1;
  if (argc > 2){
    for (i = 1; i < argc-1 && concat(argv[1], argv[i+1]); i++);
    if (i == argc-1)
      printf("Concatenation is Success!!\n");
  }
  return 0;
}

Detailed Code with error messages and safe guard.

#include <cstdio>

bool concat(char* file1, char* file2) {
  FILE* fp1 = fopen(file1, "r");
  FILE* fp2 = fopen(file2, "r");
  char ch;
  bool status = 0;
  bool err = 0;

  if(!fp1) {
    fp1 = fopen(file1, "a");
    if(!fp1) {
      printf("ERROR: Can't open %s!!\n", file1);
    }
    else {
      err = 1;
      printf("%s is created!\n", file1);
    }
  }
  else{
    fclose(fp1);
    fp1 = fopen(file1, "a");
    if(!fp1) {
      printf("ERROR: Can't open %s!!\n", file1);
    }
    else err = 1;
  }

  if(!fp2 && err) {
    printf("ERROR: Can't open %s!!\n", file2);
  }

  if (fp2 && fp1) {
    for(;(ch=fgetc(fp2)) != EOF; fputc(ch, fp1));
    fclose(fp2);
    fclose(fp1);
    status = 1;
  }
  return status;
}

int main(int argc, char** argv) {
  int i=1;
  if (argc == 1)
    printf("No destination file  selected to perform this action!\n");
  else if (argc == 2)
    printf("No files were selected to merge with %s.\n",argv[1]);
  else if (argc > 2){
    for (i = 1; i < argc-1 && concat(argv[1], argv[i+1]); i++){
      printf("%s << %s... success\n",argv[1],argv[i+1]);
    }
    if (i == argc-1)
      printf("Concatenation is Success!!\n");
  }
  return 0;
}

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s