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.