C programming perror stdio.h

In C programming the <stdio.h> perror function prints out the error message to the standard error stream.The declaration of the function is given below.

void perror(const char *sss);

sss -The pointer to a string.This string can be any message you want to include with the message that ‘perro’ prints out.For instance an additional information that might help the programmer to debug the program better.

Return type

If any error occurs the ‘perror’ function maps the error number present in the ‘errno‘ to the error message and prints it.The message will consist of-First the string pointed by sss, followed by a colon(:) and space and an appropriate error message followed by a new-line.

sss: error_message

A code example is given below;consider that the file ‘text.bin’ does not exist.

Code example

4   #define MSGLEN_MAX 256
6   int main(int argc , char **argv)
7   {
8   FILE *fp;
9   char msgbuf[MSGLEN_MAX] = “” ;
11  if ((fp = fopen(“text.bin” , “r”)) == NULL)
12  {
13  snprintf(msgbuf , MSGLEN_MAX, “%s, function %s, file
        %s, line %d”, argv[0] , __func__ , __FILE__, __LINE__);
14  perror( msgbuf );
15  }
17  getchar( );
18  return 0;
19  }

Output (in my case),

C:\My_program\C_STDIO_HEADER\stdio_perror\bin\Debug\stdio_perror.exe, function main, file C:\My_program\C_STDIO_HEADER\stdio_perror\main.c, line 13: No such file or directory

Note here,

a)argv[0] is replaced by “C:\My_program\C_STDIO_HEADER\stdio_perror\bin\Debug\stdio_perror.exe” (which the .exe file directory)
b)__func__ is replaced by “main” (the file name)
c)__FILE__ is replaced by “C:\My_program\C_STDIO_HEADER\stdio_perror\main.c” (which is the directory of the ‘main.c’ file plus it’s name)
d)__LINE__ is replaced by “13” which is the line where the error is evaluated.

So,here ‘msg’ points to the string “C:\My_program\C_STDIO_HEADER\stdio_perror\bin\Debug\stdio_perror.exe, function main, file C:\My_program\C_STDIO_HEADER\stdio_perror\main.c, line 13” and the last string “ No such file or directory” is generated by the ‘perror’ function.

‘perror’ is similar to ‘strerror‘ function.

Related links

->C snprintf stdio.h

->C preprocessor directives __LINE__ , #define

->C fopen stdio.h

->C clearerr

->C feof