用fopen
,将其设置为w
会自动清除我的文件。不过现在我试图做同样的事情open
,用open打开之前清空文件()
int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
这并不能保证该文件是空的,在开始写(?)。我怎样才能做到这一点?
用fopen
,将其设置为w
会自动清除我的文件。不过现在我试图做同样的事情open
,用open打开之前清空文件()
int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
这并不能保证该文件是空的,在开始写(?)。我怎样才能做到这一点?
添加O_TRUNC
- 最初清除文件中的所有数据。
谢谢,我刚刚在阅读手册页时没有注意到! –
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);
难以阅读[实际手册页](http://linux.die.net/man/2/open)? – ShadowRanger
@ShadowRanger请参阅下面的评论。 –