Thangaraj
Thangaraj

Reputation: 3184

How to find the fprintf() actual error?

In my program fprintf() returns -1, which indicates an error. How can I find out what actual error was?

Upvotes: 3

Views: 6506

Answers (2)

paxdiablo
paxdiablo

Reputation: 881403

You need to check the value of errno. Most library functions will set it to the specific error code and you can either look it up in errno.h or use perror or strerror to get a user-readable version.

For example:

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main (void) {
    FILE *fh = fopen ("junk", "w");
    if (fh != NULL) {
        if (fprintf (fh, "%s", "hello") < 0)
            fprintf (stderr, "err=%d: %s\n", errno, strerror (errno));
        fclose (fh);
    }
    return 0;
}

Upvotes: 4

user237419
user237419

Reputation: 9064

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

...
rc = fprintf(...)
if (rc < 0) 
    printf("errno=%d, err_msg=\"%s\"\n", errno,strerror(errno))

Upvotes: 12

Related Questions