Example of how to clear a file in C Language

Source: Internet
Author: User

Example of how to clear a file in C Language

/********************************************************************* * Author  : Samson * Date    : 02/12/2015 * Test platform: *              3.13.0-24-generic *              GNU bash, 4.3.11(1)-release  * *******************************************************************/

How can I use C to clear the content of a file directly?

The answer is in the following program code:

# Include
# Include
# Include
# Include
# Include

# Define PATHNAME "./test"
Int main ()
{
Int ret = open (PATHNAME, O_WRONLY | O_TRUNC );
If (ret =-1)
{
Printf ("open file is fail! \ N ");
Return-1;
}
Close (ret );
Return 0;
}

There is a file named test in the current directory. Run the ll command to check the file size:

Ufo @ ufo:/tmp $ ll test

-Rw-r -- 1 ufo 293 February 12 17:05 test
Ufo @ ufo:/tmp $ gcc testwrite. c

Ufo @ ufo:/tmp $./a. out

Run the command to check the size of the test file, that is, it is already 0, and no content is displayed when cat test is used.

Ufo @ ufo:/tmp $ ll test
-Rw-r -- 1 ufo 0 February 12 17:05 test

The key lies in the oflag parameter in the open function. You can use man 2 open to view the description of the open function,

O_WRONLY: indicates to open the file as write only

O_TRUNC: indicates that if the file with the parameter name pathname in open exists and only writes or reads/writes are successfully opened, the length of the file will be shortened to 0. In this way, the object content is cleared.


Related Article

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.