The difference between perror () and printf ()

I read that both perror()are printf()written to the terminal screen. But it is perror()written in stderr, and it is printf()written in stdout. So, to print errors, why perror()used, when printf()can do it.

+4
source share
6 answers

printf()cannot be written to stderr. fprintf()can.

There is no requirement that the recording on stdoutor stderrrecorded on the terminal screen - it depends on the implementation (since not all systems even have a terminal). There is also no requirement that recording in stdoutand stderrlead to recording on the same device (for example, you can redirect to a file and redirect another to a channel).

perror()will be implemented with built-in knowledge of the values ​​of the error codes represented by static errno, which is used by various functions in the standard library to report an error. The values ​​of specific values ​​are determined by the implementation (i.e., they differ between compilers and libraries).

+4
source

, stderr , (, ). stderr , , , , , .

, .

. , , .

. , ( bash)

+2

stdin stdout stderr. , , .

stderr stderr Perror. printf . Perror

fd = open (pathname, flags, mode);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}

linux

void perror(const char *s)

Perror :

s, , , , errno

C, s - , .

, 332 C

+1

fprintf (3) stderr errno (3) strerror (3)

 fprintf(stderr, "something wrong: %s\n", strerror(errno));

GNU libc ( Linux) %m :

fprintf(stderr, "something wrong: %m\n");

stderr (. stderr (3)); . syslog (3) .

\n, stderr ( ), fflush (3 )

, , fopen:

char* filename = somefilepath();
assert (filename != NULL);
FILE* f = fopen(filename, "r");
if (!f) {
   int e = errno; // keep errno, it could be later overwritten
   if (filename[0] == '/') /// absolute path
      fprintf(stderr, "failed to open %s : %s\n", filename, strerror(e));
   else { // we also try to show the current directory since relative path
      char dirbuf[128];
      memset (dirbuf, 0, sizeof(dirbuf));
      if (getcwd(dirbuf, sizeof(dirbuf)-1)) 
         fprintf(stderr, "failed to open %s in %s : %s\n", 
                 filename, dirbuf, sterror(e));
      else // unlikely case when getcwd failed so errno overwritten
         fprintf(stderr, "failed to open %s here : %s\n", 
                 filename, sterror(e));
   };
   exit(EXIT_FAILURE); // in all cases when fopen failed
 }

, errno ( e, , getcwd errno).

(, daemon (3)), (.. openlog (3) daemon), daemon stderr /dev/null

+1

perror():

stdout /dev/null, , stdout , .

+1

PError

- - . , perror, . .

Printf

, .

-1

Source: https://habr.com/ru/post/1618682/


All Articles