打印本文 打印本文  关闭窗口 关闭窗口  
C基础(C语言中的错误处理)
作者:佚名  文章来源:不详  点击数  更新时间:2008/10/22 21:29:10  文章录入:杜斌  责任编辑:杜斌

  #include<stdio.h>
  #include<setjmp.h>
  jmp_buf ebuf;
  int func();
  int main(){
  int i;
  printf("1111\n");
  i = setjmp(ebuf);
  printf("%d\n",i);
  if(i==0){
  func();
  printf("this will not be printed");
  }
  if(i==3){
  printf("3333\n");
  }
  printf("%d\n",i);
  return 0;
  }
  int func(){
  printf("2222\n");
  longjmp(ebuf,3);
  }
  输出结果:
  1111
  0
  2222
  3
  3333
  3
  相当与goto语句,当执行func函数时,由longjmp跳转到setjmp处,然后再往下执行。
  考试大提示注意的地方:longjmp(dbuf,val)其中的val不能为0,如果为0则系统默认再i=setjmp(ebuf)中i的返回值为1;
  以下函数实现了多个函数之间的跳转,其中具体代码在 动态调用链接库中
  #include <stdio.h>
  #include <windows.h>
  #include <setjmp.h>
  jmp_buf ebuf;
  int jump1();
  int jump2();
  int i;
  main(){
  i = setjmp(ebuf);
  if(i==0|i==2){
  jump1();
  }
  if(i==1){
  jump2();
  }
  }
  int jump1(){
  while(1){
  HINSTANCE hInstance;
  void (*func)();
  hInstance = LoadLibrary("my.dll");
  showGUI();
  char s[10];
  scanf("%s",&s);
  func = ( void (*)() )GetProcAddress(hInstance,s);
  if(!func){
  longjmp(ebuf,1);
  }
  (*func)();
  continue;
  }
  }
  int jump2(){
  printf("your input is wrong\n");
  longjmp(ebuf,2);
  }
  int showGUI(){
  FILE *login;
  char c;
  login = fopen("login.txt","r");
  if(!login){
  printf("file err:login\n");
  return;
  }
  while(1){
  c = fgetc(login);
  if(c == EOF){
  break;
  }
  printf("%c",c);
  }
  fclose(login);
  return 0;
  }
打印本文 打印本文  关闭窗口 关闭窗口