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!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main (int argc, char** argv) {
	
	if (argc != 2) {
		fprintf(stderr, "usage: ./error_test <file> \n");
		exit(1);
	}

	
	/* open any non-existing file to provoke an error message */
	
	
	if (NULL == fopen(argv[1], "r")) {
		perror ("fopen() failed");
		fprintf(stderr, "fopen() failed\n");
		fprintf(stderr, "fopen() failed: Error code %d\n", errno);
		fprintf(stderr, "fopen() failed: Error code %s\n", strerror(errno));
	} 
	return 0;
}

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.

This article has been dead for over six months. Start a new discussion instead.