我使用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