C/Development/error

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

Define Macro for string variable

<source lang="cpp">

  1. include <stdio.h>
  2. if !defined( HELLO_MESSAGE )
  # error "You have forgotten to define the header file name."
  1. endif

char *format = "%s",

    *hello = HELLO_MESSAGE;

int main() {

 printf ( format, hello );

}


      </source>


Get pointer to error message string: how to use strerror

<source lang="cpp">

  1. include <stdio.h>
  2. include <string.h>
  3. include <errno.h>

int main () {

 FILE *file;
 file = fopen ("my.txt","r");
 
 if (file == NULL)
   printf ("Error opening file my.txt: %s\n", strerror(errno));
 
 return 0;

}

      </source>


Preprocessor: error

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 int i;
 i = 1;
  1. error This is an error message.
 printf("%d", i); /* this line will not be compiled */
 return 0;

}


      </source>


Preprocessor: line

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 int i;

/* reset line number to 1000 and file name to myprog.c

  • /
  1. line 1000 "myprog.c"
  2. error Check the line number and file name.
 return 0;

}


      </source>


Print error message: how to use perror

<source lang="cpp">

  1. include <stdio.h>

int main () {

 FILE *file;
 
 file=fopen ("my.ent", "rb");
 
 if (file==NULL)
   perror ("An error has occurred");
 else
   fclose (file);
 return 0;

}


      </source>


Reset error indicators: writing errors

<source lang="cpp">

  1. include <stdio.h>

int main () {

 FILE * pFile;
 pFile = fopen("f.txt","r");
 if (pFile==NULL) 
     perror ("Error opening file");
 else {
     fputc ("v",pFile);
     if (ferror (pFile)) {
         printf ("Error Writing to f.txt\n");
         clearerr (pFile);
     }
     fgetc (pFile);
     if (!ferror (pFile))
         printf ("No errors.\n"); 
     fclose (pFile);
 }
 return 0;

}


      </source>