如何在使用fstream打开文件时截断文件 [英] How to truncate a file while it is open with fstream

查看:568
本文介绍了如何在使用fstream打开文件时截断文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用

std::fstream fs(mypath, std::fstream::out | std::fstream::trunc);

但我需要读取文件,截断它,然后用相同的文件句柄(所以整个操作是原子的)。任何人?

but I need to read the file, truncate it, then write new contents all with the same file handle (so the whole operation is atomic). Anyone?

推荐答案

文件流不支持截断,除非打开文件。此外,操作不会是原子反正:至少,在POSIX系统上,你可以愉快地读取和写入已经由另一个进程打开的文件。

File streams don't support truncation except when opening a file. Also, the operations wouldn't be "atomic" anyway: at least, on POSIX systems you can happily read and write a file already opened by another process.

这篇关于如何在使用fstream打开文件时截断文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆