fprintf 和 perror 的理解1

程序中的两种出错处理:

第一种: 用fprintf

   2:  #include <string.h>
   3:  #include <errno.h>
   4:  #include <stdlib.h>
   5:   
   1:  #include <stdio.h>
   6:  int main(void)
   7:  {
   8:      FILE *fp;
   9:   
  10:      if((fp = fopen("1.c", "r")) == NULL)
  11:      {
  12:          fprintf(stderr, "fopen error! %s", strerror(errno));
  13:          exit(-1);
  14:      }
  15:      return 0;
  16:  }

image

可以看出,这种输出结果不会自动换行。而且参数较多。

第二种、perror

   1:  #include <stdio.h>
   2:  #include <stdlib.h>
   3:   
   4:  int main(void)
   5:  {
   6:      FILE *fp;
   7:   
   8:      if((fp = fopen("1.c", "r")) == NULL)
   9:      {
  10:          perror("fopen error!");
  11:          exit(-1);
  12:      }
  13:      return 0;
  14:  }

image

可以看出:用perror的输出会自动换行,且自动加上一个冒号和错误提示。推荐!

原文地址:https://www.cnblogs.com/pengdonglin137/p/2952414.html