perror() Function - example program in C

By: Lakshmi Emailed: 1589 times Printed: 2037 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The perror() function is another of C's error-handling tools. When called, perror() displays a message on stderr describing the most recent error that occurred during a library function call or system call. The prototype, in STDIO.H, is

void perror(char *msg);

The argument msg points to an optional user-defined message. This message is printed first, followed by a colon and the implementation-defined message that describes the most recent error. If you call perror() when no error has occurred, the message displayed is no error.

A call to perror() does nothing to deal with the error condition. It's up to the program to take action, which might consist of prompting the user to do something such as terminate the program. The action the program takes can be determined by testing the value of errno and by the nature of the error. Note that a program need not include the header file ERRNO.H to use the external variable errno. That header file is required only if your program uses the symbolic error constants. Sample program below illustrates the use of perror() and errno for handling runtime errors.

Using perror() and errno to deal with runtime errors.

1: /* Demonstration of error handling with perror() and errno. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <errno.h>
6:
7: main()
8: {
9:     FILE *fp;
10:     char filename[80];
11:
12:     printf("Enter filename: ");
13:     gets(filename);
14:
15:     if (( fp = fopen(filename, "r")) == NULL)
16:     {
17:         perror("You goofed!");
18:         printf("errno = %d.\n", errno);
19:         exit(1);
20:     }
21:     else
22:     {
23:         puts("File opened for reading.");
24:         fclose(fp);
25:     }
26:     return(0);
27: }
Enter file name: list19_4.c
File opened for reading.
Enter file name: notafile.xxx
You goofed!: No such file or directory
errno = 2.

ANALYSIS: This program prints one of two messages based on whether a file can be opened for reading. Line 15 tries to open a file. If the file opens, the else part of the if loop executes, printing the following message:

File opened for reading.

If there is an error when the file is opened, such as the file not existing, lines 17 through 19 of the if loop execute. Line 17 calls the perror() function with the string "You goofed!". This is followed by printing the error number. The result of entering a file that does not exist is

You goofed!: No such file or directory.
errno = 2

 


DO include the ERRNO.H header file if you're going to use the symbolic errors.

DON'T include the ERRNO.H header file if you aren't going to use the symbolic error constants.

DO check for possible errors in your programs. Never assume that everything is okay.



C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(2)


1. View Comment

Nice example. I think this is more idiomatic tho'.


/* Demonstration of error handling with perror() and errno. */

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

int main(int argc, char** argv)
{
FILE *fp;

if (fp = fopen(argv[1], "r"))
{
printf("File %s opened for reading.\n", argv[1]);
fclose(fp);
}
else
{
perror("You goofed!");
printf("errno = %d.\n", errno);
exit(1);
}
return 0 ;
}


View Tutorial          By: John Morrison at 2010-03-28 14:55:07
2. View Comment

Notice that on an UNIX environment (including Linux, Mac and iPhone), the filesystem is case sensitive, thus you should always include error.h and not ERROR.H.

View Tutorial          By: Alejandro segovia at 2011-02-22 11:08:23

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Lakshmi
Exporting a Certificate Authenticating Your Public Key example using keytool in Java
while and do-while example in Java
Common SQL Commands
Data Access Technologies in Java
perror() Function - example program in C
Struts-GUI and Struts Console
Variable-length Argument Lists sample program in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Use ImageButtonBean for Image based Form Submits in Struts
break and continue loops in C
Arguments - Call by Value in C
Using command-line arguments in C++
How to handle Exceptions in C++
Gauge sample program in J2ME
What is Reflection? - getConstructors(), getFields(), and getMethods()

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Printing a simple histogram in C
Using memset(), memcpy(), and memmove() in C
UNIX read and write system calls sample program in C
Open, Creat, Close, Unlink system calls sample program in C
perror() Function - example program in C
assert() Function Example program in C
lseek() sample program in C
Find square and square root for a given number in C
Listing Files and Directories sample program in C
register Variables in C
Using realloc() Function in C
Character Arrays in C
Macro Substitution using #define in C
Sum of the elements of an array in C
scanf and sscanf sample program in C
Most Emailed Articles (in C)
Open, Creat, Close, Unlink system calls sample program in C
Using malloc() Function in C
Increment and Decrement Operators in C
Using qsort() and bsearch() with strings - example program in C
The C Character Set
Formatting with printf in C
Simple arithmetic calculations in C
Relational and Logical Operators in C
While and For Loops in C
getch and ungetch in C
register Variables in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Pointers and Arrays in C
Command-line Arguments in C
Variable-length Argument Lists sample program in C