Viết hàm main với tham số đầu vào từ dòng lệnh

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


/*----------------------------------------------------------------------
Cach chay chuong trinh
//--------------------------------------------------------------------*/
int in_parameter(int argc, char* argv[], FILE* & inf, FILE* & outf)
{
  int i;

  if (argc<5) {
        printf("USAGE: %s -input infile -output outfile\n", argv[0]);	
        return (0);
  }

  if (strcmp(argv[1], "-input") != 0) {
        printf("USAGE: %s -input infile -output outfile\n", argv[0]);	
        return (0);
  }

  if ((inf = fopen(argv[2], "r")) == 0) {
          printf("Can't open input file.\n");
          return (0);
  }

  if (strcmp(argv[3], "-output") != 0) {
        printf("USAGE: %s -input infile -output outfile\n", argv[0]);	
        return (0);
  }

  if ((outf = fopen(argv[4], "w")) == 0) {
          printf("Can't open output file.\n");
          return (0);
  }


  return (1);
}


/*----------------------------------------------------------------------

// Xuat file 
//--------------------------------------------------------------------*/
int PrintFile(FILE* file, int n)
{
  fprintf(file, "%d", n+1);
  fclose(file);
}


/*----------------------------------------------------------------------
// Doc file dau vao
// 
//--------------------------------------------------------------------*/
int ReadFile(FILE* file, int &  n)
{
  int i, j;

  if (fscanf(file, "%d", &n) != 1) { 
     fclose(file);
     return (0);
  }

  fclose(file);
  return (1);
}


/*----------------------------------------------------------------------
// Chuong trinh chinh
//--------------------------------------------------------------------*/
int main (int argc, char** argv) 
{
  int        n;
  FILE*      in_file;
  FILE*      out_file;

  if (!in_parameter(argc, argv, in_file, out_file)){
      return (1);
  }


  /*----------
  // Doc input file.
  //--------*/
    if (!ReadFile(in_file, n)) { // Du lieu bi dinh dang sai hoac khong co du lieu trong file input
      printf("Program terminating\n");
      return (1);
    }

  // Print the output.
  //--------*/
    PrintFile(out_file, 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 )

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

%d bloggers like this: