errno - perror vs fprintf + strerror

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Is0r Is0r is offline Offline Nov 11th, 2009, 11:23 am |
-1
Hi!

From the manpages I know, that perror evaluates the errno. So
using perror and fprintf + strerror, as coded in my example below, should result in the same error messages, but they do not.
The execution of the program leads to the following result:

bash> ./errno_test blub
fopen() failed: No such file or directory
fopen() failed
fopen() failed: Error code 29
fopen() failed: Error code Illegal seek

Can someone explain, where this behavior comes from? I think
fopen calls open, and open might invoke something such as a seek function. Is the errno set inappropriately? Or am I wrong about the
assumption, that perror and fprintf + strerror should cause the same output?

Thanks and Regards!
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5.  
  6. int main (int argc, char** argv) {
  7.  
  8. if (argc != 2) {
  9. fprintf(stderr, "usage: ./error_test <file> \n");
  10. exit(1);
  11. }
  12.  
  13.  
  14. /* open any non-existing file to provoke an error message */
  15.  
  16.  
  17. if (NULL == fopen(argv[1], "r")) {
  18. perror ("fopen() failed");
  19. fprintf(stderr, "fopen() failed\n");
  20. fprintf(stderr, "fopen() failed: Error code %d\n", errno);
  21. fprintf(stderr, "fopen() failed: Error code %s\n", strerror(errno));
  22. }
  23. return 0;
  24. }

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC