C/Development/Debug

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Copy a file in debug mode

#include <stdio.h>
#include <stdlib.h>
#define DEBUG
int main(int argc, char *argv[])
{
  FILE *from, *to;
  char ch;
  /* check number of command line arguments */
  if( argc != 3) {
    printf("Usage: copy <source> <destination>\n");
    exit(1);
  }
  /* open source file */
  if((from = fopen(argv[1], "rb"))==NULL) {
    printf("Cannot open source file.\n");
    exit(1);
  }
  /*open destination file */
  if((to = fopen (argv[2], "wb")) ==NULL) {
    printf("Cannot open destination file.\n");
    exit(1);
  }
  while(!feof(from)) {
    ch = fgetc(from);
    if(ferror(from)) {
      printf("Error reading source file.\n");
      exit(1);
    }
    if(!feof(from)) {
      fputc(ch, to);
    }
    if(ferror(to)) {
      printf("Error writing destination file.\n");
      exit(1);
    }
  }
  fclose(from);
  fclose(to);
  return 0;
}


Copy a file in four debug level

#include <stdio.h>
#include <stdlib.h>
/* DEBUG levels:
          0: no debug
          1: display byte read from source file
          2. display byte written to destination file
          3: display bytes read and bytes written
*/
#define DEBUG 2
int main(int argc, char *argv[])
{
  FILE *in, *out;
  unsigned char ch;
  /* see if correct number of command line arguments */
  if(argc!=4) {
    printf("Usage: code <in> <out> <key>");
    exit(1);
  }
  /* open input file */
  if((in = fopen(argv[1], "rb"))==NULL) {
    printf("Cannot open input file.\n");
    exit(1);
  }
  /* open output file */
  if((out = fopen(argv[2], "wb"))==NULL) {
    printf("Cannot open output file.\n");
    exit(1);
  }
  while(!feof(in)) {
    ch = fgetc(in);
#if DEBUG == 1 || DEBUG == 3
    putchar(ch);
#endif
    ch = *argv[3] ^ ch;
#if DEBUG >= 2
    putchar(ch);
#endif
    if(!feof(in)) fputc(ch, out);
  }
  fclose(in);
  fclose(out);
  return 0;
}


Debugging using pre-processing directives

#include <stdio.h>
#include <stdlib.h>
#define test
#define testf
int sum(int, int);
int product(int, int);
int difference(int, int);
int main()
{
  int i = 0;
  int j = 0;
  int a = 10, b = 5;
  int result = 0;
  int (*pfun[3])(int, int);

  pfun[0] = sum;
  pfun[1] = product;
  pfun[2] = difference;
  for(i = 0 ; i < 3 ; i++)
  {
    j = i;
    #ifdef test
    printf("\nRandom number = %d", j );
    #endif
    result = pfun[j](a , b);
    printf("\nresult = %d", result );
  }
  result = pfun[1](pfun[0](a , b), pfun[2](a , b));
  printf("\n\nThe product of the sum and the difference = %d\n", result);
}
int sum(int x, int y){
  #ifdef testf
  printf("\nFunction sum called.");
  #endif
  return x + y;
}
int product( int x, int y ){
  #ifdef testf
  printf("\nFunction product called.");
  #endif
  return x * y;
}
int difference(int x, int y){
  #ifdef testf
  printf("\nFunction difference called.");
  #endif
  return x - y;
}