Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Language%20in%20C%20Interview%20Questions%20and%20Answers

Question: How do I write code that would get error number and display error message if any standard error occurs?

Answer: Following code demonstrates this.

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

main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( "C:file.txt", "r" ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( "n%s", errmsg ) ;
}
}
Here, we are trying to open 'file.txt' file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in 'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook