C 程序结束时的错误处理

C error handling at end of program

我已经阅读了很多关于 C 中错误处理的教程和初学者问题。它们(大部分)似乎都朝着这个方向发展:

int main(){

if(condition){
    fprintf(stderr, "Something went wrong");
    exit(EXIT_FAILURE); // QUIT THE PROGRAM NOW, EXAMPLE: ERROR OPENING FILE
}

exit(0)
}

我的问题:C 中是否有任何特定的函数可以让我捕获错误,但仅在程序退出时影响程序 (main) 的状态?我的想法示例:

int main(){

if(condition){
    fprintf(stderr, "Something went wrong");
    // Continue with code but change exit-status for the program to -1 (EXIT_FAILURE)
}

exit(IF ERROR CATCHED = -1)
}

或者我是否必须创建一些自定义函数或使用一些指针?

好吧,如果您想继续,您不必调用 exit(),对吗? 您可以使用影响 main() 退出代码的变量。

#include <stdio.h>

int main(void){
   int main_exit_code = EXIT_SUCCESS;

   if(condition){
      fprintf(stderr, "Something went wrong");
      main_exit_code = -1; /* or EXIT_FAILURE */
   }

   return (main_exit_code);
}

但请注意,根据您遇到的错误类型,在所有情况下都继续执行可能没有意义。所以,我会留给你决定。

exitint 作为状态,您可以将此状态存储在变量中,并在末尾使用此值调用 exit

int main(void)
{
    int res = EXIT_SUCCESS;

    if (condition) {
       fprintf(stderr, "Something went wrong");
       res = EXIT_FAILURE;
    }
    /* Continue with code */
    exit(res);
}