8.2. Empty a File
Table of Contents
Sometimes we want empty the file contents instead of deleting the file
and then recreating it. Opening a filehandle with flag
O_TRUNC will clear
all data from the file.
This lab builds on Lab 5. Writing to a file.
You need three flags to empty or create the file using open.
O_WRONLYopens the file in write only mode.
O_TRUNCempties the file of any data.
O_CREATcreates the file if it does not exit.
This flags requires that file permissions are send with the the
Required Include Files
char *file_name = "test-empty.txt"; int flags = O_WRONLY | O_TRUNC | O_CREAT; int file_permissions = 0644; // open a file handle that creates or empties the file. int empty_fd = open(file_name, flags, file_permissions); close(empty_fd);
Task: Empty a File
Create a file called
lab8.2.c for this task.
Create a function that empties an existing file or creates the file if it does not exist.
The function should accept the name or path of the file to empty.
Hint: Use a pointer to a char array.
The function should return a
trueif the file emptied successfully.
falseif an error occurred while emptying or creating the file.
Test the function by:
Writing some data to the file
Emptying the file
Verifying that the file is empty.