Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable with perror

Tags:

c

I would like to print a variable with perror, i.e. I would like to write something like perror("error with something %s", my_var)

Is it possible and how can I do it?

like image 228
Simon Avatar asked Jul 12 '14 21:07

Simon


People also ask

How do I print perror?

The perror() function prints an error message to stderr . If string is not NULL and does not point to a null character, the string pointed to by string is printed to the standard error stream, followed by a colon and a space.

How do I print an error number?

Your program can use the strerror() and perror() functions to print the value of errno. The strerror() function returns a pointer to an error message string that is associated with errno. The perror() function prints a message to stderr.

Does perror add a newline?

The perror() function prints a message to the standard error stream. The output includes first the string referenced by the pointer argument, if any; then a colon and a space, then the error message that corresponds to the current value of the errno variable, ending with a newline character.

Why is perror printing success?

Essentially the string representation of "errno" a global variable is printed out along with your arguments. If you have no errors (errono = 0). This is causing your program to print "SUCCESS".


2 Answers

Use fprintf() instead

fprintf(stderr, "error with something %s", my_var);
perror("");

Otherwise you can build a string, then pass it to perror

char yourstring[100];
snprintf(yourstring, sizeof yourstring, "error with something %s", my_var);
perror(yourstring);
like image 95
pmg Avatar answered Sep 30 '22 21:09

pmg


I know it has already been answered, but I feel like there is a cleaner version of it

fprintf(stderr, "Error on line %d : %s\n", __LINE__, strerror(errno));
// Error on line 42 : Wrong argument
like image 33
John Avatar answered Sep 30 '22 19:09

John