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?
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.
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.
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.
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".
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With