1

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)

  • 1
    If you want an empty file, you shouldn't write any bytes into it. There's a POSIX system call for this, `truncate(2)` which avoids even having to open the file, letting you set its length to 0. Or open it with `O_TRUNC` like a shell redirect would, or if already open, use `ftruncate`. – Peter Cordes Apr 06 '22 at 07:19
  • 1
    Also, seems like you haven't understood the difference between C strings (implicit terminated, indicated by a `0` byte) vs. explicit-length buffers like an array + length. Files have a length stored separately from the data, so `ls -l` can tell you the file length without having to open+read every file searching for a `0` bytes (instead using the `stat` system call; try `strace ls -l` to see the syscalls it makes). And so files can contain multiple zeros, just like an array of `char` or `int` can! Arbitrary binary data pretty much needs to be explicit-length; that's why `write()` takes a len – Peter Cordes Apr 06 '22 at 07:34

1 Answers1

0

Why don't you only try to open as following? It truncates the file as you expect.

open(*++argv, O_TRUNC | O_WRONLY);