如何找到fprintf()的实际错误

How to find the fprintf() actual error?

本文关键字:错误 何找 fprintf      更新时间:2023-10-16

在我的程序中,fprintf()返回-1,表示错误。我怎样才能知道实际的错误是什么?

#include <errno.h>
#include <string.h>
...
rc = fprintf(...)
if (rc < 0) 
    printf("errno=%d, err_msg="%s"n", errno,strerror(errno))

需要查看"errno"的值。大多数库函数将其设置为特定的错误代码,您可以在errno.h中查找它,也可以使用perrorstrerror来获得用户可读的版本。

例如:

#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: %sn", errno, strerror (errno));
        fclose (fh);
    }
    return 0;
}