strerror
suggest changeIf perror is not flexible enough, call strerror from <string.h> for a description of an error number. Copy errno immediately: a later library call may change it. The string returned by strerror may be overwritten by a later call, including a call from another thread. Do not rely on it remaining valid.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fout;
int last_error = 0;
if (argc < 2)
return EXIT_FAILURE;
if ((fout = fopen(argv[1], "w")) == NULL) {
last_error = errno;
errno = 0;
}
/* Other work can continue here. Report the saved error afterward. */
if (last_error) {
fprintf(stderr, "fopen: Could not open %s for writing: %s\n",
argv[1], strerror(last_error));
fputs("Cross fingers and continue\n", stderr);
}
if (fout != NULL && fclose(fout) == EOF)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents