2015-11-11 122 views
-1

fopen,将其设置为w会自动清除我的文件。不过现在我试图做同样的事情open用open打开之前清空文件()

int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); 

这并不能保证该文件是空的,在开始写(?)。我怎样才能做到这一点?

+0

难以阅读[实际手册页](http://linux.die.net/man/2/open)? – ShadowRanger

+0

@ShadowRanger请参阅下面的评论。 –

回答

1

添加O_TRUNC - 最初清除文件中的所有数据。

+0

谢谢,我刚刚在阅读手册页时没有注意到! –

1
O_TRUNC flag truncates the file when opening. It can be used. 
int file = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);