问题描述
|
在我的程序中,“ 0”返回-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
中查找它,或者使用perror
或strerror
获取用户可读的版本。
例如:
#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\",strerror (errno));
fclose (fh);
}
return 0;
}