开发者

Understanding a piece of code in C++

Can you help me understand the followin开发者_开发技巧g code?

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

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


Calling errorexit("Error Message") will print "Error Message" to the standard error stream (often in a terminal) and exit the program. Any programs (such as the shell) that called your program will know that the there was an error since your program exited with a non-zero status.


It is printing out the string pointed to by pchar to the standard error output via fprintf and then forcing the application to exit with a return code of 1. This would be used for critical errors when the application can't continue running.


That function prints the provided string and a newline to stderr and then terminates the current running program, providing 1 as the return value.

fprintf is like printf in that it outputs characters, but fprintf is a little different in that it takes a file handle as an argument. I this case stderr is the file handle for standard error. This handle is already defined for you by stdio.h, and corresponds to the error output stream. stdout is what printf outputs to, so fprintf(stdout, "hello") is equivalent to printf("hello").

exit is a function that terminates the execution of the current process and returns whatever value was its argument as the return code to the parent process (usually the shell). A non-zero return code usually indicates failure, the specific value indicating the type of failure.

If you ran this program from the 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;
}

You'd see this output:

Hello world!
Goodbye :(

And your shell would show "1" as the return value (in bash, you can view the last return code with echo $?).

Note that "Just kidding!" would not be printed, as errorexit calls exit, ending the program before main finishes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜