I would like to write a function able to delete contents of files.
I have some thoughts of how to do it and here is the program that come up from them:
/*fclr - clear file contents*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char* argv[]){
int fd;
if(--argc == 0)
fprintf(stderr, "Incorrect syntax. Usage: cat <filename1> <filname2> ... <filenameN>.\n");
while(--argc > 0){
char c = EOF;
if((fd = open(*++argv, O_WRONLY, 0)) == -1)
fprintf(stderr, "Unable to open the file.\n");
lseek(fd, 0, SEEK_SET); //lseek here is redundant.
write(fd, &c, sizeof(char));
close(fd);
}
}
Basically, I suppused, if a file is seen a very big array of characters, is has to have and end in memory. So as well as \0 works for stings, I thought EOF will do for actual files, but is not working. After the file is ran, the content is still there.
Do you have any suggestion to solve this problem.
(I do know that opening a file with fopen on "w" mode will delete the whole content, but I would like to achieve the same result with low level functions)