2011-03-16 46 views
0

你能帮我理解下面的代码吗?了解C++中的一段代码

void errorexit(char *pchar) { 
    // display an error to the standard err. 

    fprintf(stderr, pchar); 
    fprintf(stderr, "\n"); 
    exit(1); 
} 
+1

你知道些什么? – Thomas 2011-03-16 18:36:42

回答

0
调用

errorexit("Error Message")将打印“错误消息”到标准错误流(通常在终端),并退出该程序。任何调用程序的程序(例如shell)都会知道程序以非零状态退出时出现错误。

0

它将pchar所指向的字符串打印到通过fprintf输出的标准错误,然后强制应用程序以1的返回码退出。当应用程序无法继续运行时,这将用于严重错误。

0

该函数将提供的字符串和换行符打印到stderr,然后终止当前正在运行的程序,提供1作为返回值。

fprintf就像printf在于其输出字符,但fprintf是,它需要一个文件句柄作为参数稍有不同。我这种情况stderr是标准错误的文件句柄。这个句柄已经由stdio.h为你定义,并且对应于错误输出流。 stdout是什么printf输出到,所以fprintf(stdout, "hello")相当于printf("hello")

exit是一个函数,它终止当前进程的执行并将其参数的任何值作为返回代码返回给父进程(通常是shell)。非零返回码通常表示失败,具体值表示失败的类型。

#include <stdio.h> 
#include "errorexit.h" 

int main(int argc, char* argv[]) 
{ 
    printf("Hello world!\n"); 
    errorexit("Goodbye :("); 
    printf("Just kidding!\n"); 

    return 0; 
} 

你会看到这样的输出:

如果你从shell运行此程序

Hello world! 
Goodbye :(

而且你的shell会显示 “1” 的返回值(在bash,您可以使用echo $?查看最后的退货代码)。

请注意“只是在开玩笑!” 不是将被打印,因为errorexit调用exit,在main完成之前结束程序。