Ondo
Ondo

Reputation: 45

How to check if a file exist, delete content or create it

i would like to check if a file exist, delete content if it exists or create it if not.

I have tried :

open("screenshot.bmp", O_CREAT | O_RDWR | O_TRUNC);

But the file don't update if it already exists, if it doesn't the file is created correctly.

if ((fd = open("screenshot.bmp", O_CREAT, S_IRWXU)) > -1)
    return (-1);
close (fd);
if ((fd = open("screenshot.bmp", O_TRUNC)) > -1)
    return (-1);

But the file looks corrupted/empty after that (it should be filled by the rest of my code)

I also tried other ways.

Thanks for help !

Upvotes: 0

Views: 730

Answers (1)

Serpent27
Serpent27

Reputation: 332

Try using FILE *fd = fopen("screenshot.bmp", "w");

Accorsing to tutorialspoint:

FILE *fopen(const char *filename, const char *mode)

"w"

Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.

Update: OP says fopen(...) isn't allowed, but...

According to the docs you can achieve the same result as the fopen(...) call using:

open (filename, O_WRONLY | O_CREAT | O_TRUNC, mode)

For example (from the docs):

The following example opens the file /tmp/file, either by creating it (if it does not already exist), or by truncating its length to 0 (if it does exist). In the former case, if the call creates a new file, the access permission bits in the file mode of the file are set to permit reading and writing by the owner, and to permit reading only by group members and others.

If the call to open() is successful, the file is opened for writing.

#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "/tmp/file";
...
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, mode);
...

Upvotes: 3

Related Questions