我尝试在linux中打开这样的文件.如果退出,它将覆盖现有的一个.这就是我想要的.
fout = open(out_file_name, O_WRONLY | O_CREAT, 644);
Run Code Online (Sandbox Code Playgroud)
但是,如果现有的是1024字节,那么当我以上述方式打开并写入800个新字节时.我仍然看到以前内容结尾的224个字节.
我怎么能让它只有我写的800字节?
Dan*_*ego 22
您希望使用该O_TRUNC标志open(),通过将其与您上面的现有标志进行OR运算:
int fout = open(out_file_name, O_WRONLY | O_CREAT | O_TRUNC, 644);
Run Code Online (Sandbox Code Playgroud)
这将截断文件.以下是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.
Run Code Online (Sandbox Code Playgroud)