[英]Partially truncating a stream (fstream or ofstream) in C++
I am trying to partially truncate (or shorten) an existing file, using fstream. 我试图使用fstream部分截断(或缩短)现有文件。 I have tried writing an EOF character, but this seems to do nothing. 我曾尝试过写一个EOF角色,但这似乎什么也没做。
Any help would be appreciated... 任何帮助,将不胜感激...
I don't think you can. 我认为你不能。 There are many functions for moving "up and down" the wrapper hierarchy for HANDLE<->int<->FILE *
, at least on Windows, but there is no "proper" to extract the FILE *
from an iostreams object (if indeed it is even implemented with one). 有很多函数可以在HANDLE<->int<->FILE *
“上下”移动包装器层次结构,至少在Windows上,但是没有“正确”从iostreams对象中提取FILE *
(如果确实如此)它甚至实现了一个)。
You may find this question to be of assistance. 您可能会发现这个问题对您有所帮助。
Personally I would strongly recommend steering clear of iostreams, they're poorly designed, heavily C++, and nasty to look at. 就个人而言,我强烈建议避开iostreams,它们的设计很差,很重要的C ++,并且看起来很讨厌。 Take a look at Boost's iostreams , or wrap stdio.h if you need to use classes. 看看Boost的iostreams ,或者如果你需要使用类,请包装stdio.h 。
The relevant function for stdio is ftruncate() . stdio的相关函数是ftruncate() 。
The Boost.Interprocess library defines a portable truncate
function. Boost.Interprocess库定义了一个可移植的truncate
函数。 For some reason it is not documented, but you can find it this header file . 由于某种原因,它没有记录,但你可以找到它头文件 。
It'll depend on the OS. 这取决于操作系统。 Most OSes support this, but in different ways. 大多数操作系统都支持这种方式,但方式不同。 On Windows, there's a SetEndOfFile()
. 在Windows上,有一个SetEndOfFile()
。 On Unix and similar systems, you lseek
to where you want the file to end, and do an lwrite
of zero bytes there. 在Unix和类似的系统,你lseek
到你想要的文件结束,并做一个lwrite
的零个字节存在。 Other OSes undoubtedly use other methods. 其他操作系统无疑使用其他方法。
I bit the bullet in the end and read the part of the file to be kept to an array then re-wrote it. 我最后咬了一下子弹并读取了要保存到阵列的文件部分然后重新编写它。 It's not the best solution - but as the files will always be small I have decided to accept this method. 这不是最好的解决方案 - 但由于文件总是很小,我决定接受这种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.