MOHAMED MOHAMED - 3 months ago 12x
Linux Question

How to make open() truncate an existing file

I m opening a file with


I want that
function discard the file content if it already exists, and then the file is treated as a new empty file.

I tried with the following code:

int open_file(char *filename)
int fd = -1;
fd = open(filename, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
printf("Couldn't create new file %s: %s\n",
filename, strerror(errno));
return -1;
return 0;

but I got the following error:

Couldn't create new file kallel333: File exists

What am I missing?

sas sas

Please add O_TRUNC flag and remove O_EXCL.

open(filename, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

From open man page -

O_EXCL Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists, then open() will fail.

O_TRUNC If the file already exists and is a regular file and the access mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length