944,111 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 2463
  • C RSS
Nov 11th, 2009
-1

errno - perror vs fprintf + strerror

Expand Post »
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!
  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. }
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Is0r is offline Offline
1 posts
since Nov 2009
Aug 6th, 2010
0
Re: errno - perror vs fprintf + strerror
fopen() failed: No such file or directory
fopen() failed
fopen() failed: Error code 2
fopen() failed: Error code No such file or directory

this is the output for your code on VC++ 2010 Express Edition that is one correctly.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
costica_is is offline Offline
1 posts
since Aug 2010

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: How to use Arrays of Structures in C
Next Thread in C Forum Timeline: Looping problem.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC