8.2. Empty a File#
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.
Note
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 theopencommand.
Template Code#
Required Include Files
#include <fcntl.h>
Basic Usage
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
boolvalue.Return
trueif the file emptied successfully.Return
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.
Source & license
Reproduced verbatim, without modification from © 2022, BilimEdtech Labs, licensed under Creative Commons Attribution 4.0 International (CC BY 4.0).
Source page: https://labs.bilimedtech.com/operating-systems/8/2.html
See LICENSE for the full license text.