Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

c - When should I use perror("...") and fprintf(stderr, "...")?

Reading the man pages and some code did not really help me in understanding the difference between - or better, when I should use - perror("...") or fprintf(stderr, "...").

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling perror will give you the interpreted value of errno, which is a thread-local error value written to by POSIX syscalls (i.e., every thread has it's own value for errno). For instance, if you made a call to open(), and there was an error generated (i.e., it returned -1), you could then call perror immediately afterwards to see what the actual error was. Keep in mind that if you call other syscalls in the meantime, then the value in errno will be written over, and calling perror won't be of any use in diagnosing your issue if an error was generated by an earlier syscall.

fprintf(stderr, ...) on the other-hand can be used to print your own custom error messages. By printing to stderr, you avoid your error reporting output being mixed with "normal" output that should be going to stdout.

Keep in mind that fprintf(stderr, "%s ", strerror(errno)) is similar to perror(NULL) since a call to strerror(errno) will generate the printed string value for errno, and you can then combined that with any other custom error message via fprintf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...