我尝试在 Linux 中打开这样的文件。如果退出,它将覆盖现有的。这就是我想要的。
fout = open(out_file_name, O_WRONLY | O_CREAT, 644);
但是,如果现有的是1024字节,当我以上述方式打开并写入800个新字节时。 我仍然看到之前内容末尾的 224 字节。
我怎样才能让它只有我写的800字节?
最佳答案
您想将 O_TRUNC
标志用于 open()
,方法是将其与上面现有的标志进行 OR 运算:
int fout = open(out_file_name, O_WRONLY | O_CREAT | O_TRUNC, 644);
这将截断文件。以下是 open(2) 手册页中的信息。
O_TRUNC
If the file already exists and is a regular file and the open
mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be
truncated to length 0. If the file is a FIFO or terminal device
file, the O_TRUNC flag is ignored. Otherwise the effect of
O_TRUNC is unspecified.
关于c - 如何打开覆盖现有内容的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092040/