Wonderful use of the exit function

Source: Internet
Author: User

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.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.