我使用open()
函數打開文件。如何使open()截斷現有文件
我想open()
函數丟棄文件內容,如果它已經存在,然後該文件被視爲一個新的空文件。
我試着用下面的代碼:
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;
}
close(fd);
return 0;
}
,但我得到了以下錯誤:
Couldn't create new file kallel333: File exists
我缺少什麼?
要刪除或截斷文件 – sas
您是否嘗試添加O_TRUNC標誌。 – sas
@sas watever,目標是有一個新的空的打開的文件。我不想得到這個錯誤 – MOHAMED