Wonderful use of the exit function
A program is written to determine whether a file exists:
# Include <stdio. h>
Main ()
{
FILE * fp;
Fp = fopen ("/home/wang/my/ct2.c", "r + ");
If (fp = NULL)
{
Printf ("there is not this file! \ N ");
}
Else
Printf ("the file is exist! \ N ");
Fclose (fp );
}
R + indicates opening a text file for reading and writing.
If the ct2.c document in the/home/wang/my/directory exists,
The program runs as follows:
The file is exist!
The running result is correct!
If the ct2.c document in the/home/wang/my/directory does not exist,
The program runs as follows:
There is not this file!
Segmentation fault (core dumped)
The running result is incorrect!
You need to use the exit function to modify the program to the following form:
# Include <stdio. h>
Main ()
{
FILE * fp;
Fp = fopen ("/home/wang/my/ct2.c", "r + ");
If (fp = NULL)
{
Printf ("there is not this file! \ N ");
Exit (0 );
}
Else
Printf ("the file is exist! \ N ");
Fclose (fp );
}
The program running result is:
There is not this file!
The running result is correct! "Segmentation fault (core dumped)" is missing in the result )"!
The exit function is used to close all files and terminate ongoing programs. When an error is detected,
After modification, run.