开发者

Changing binary file

I have a file on windows. I'm writing in C++. I have a problem where I need to remove some bytes from the end of the file. I am using ifstream,开发者_高级运维 but I don't know how to remove those chars, simple put '\0' in the file or what ?


On linux machines, use truncate(): http://linux.die.net/man/2/truncate

On the Windows machines, use SetEndOfFile():

http://msdn.microsoft.com/en-us/library/aa365531%28v=vs.85%29.aspx

Both are OS dependent calls.


You can't portably change the size of a file; the only way to do it is to copy the file to a temporary, then delete the original and rename the temporary.

If it's just a case of truncating the file, both Windows and Unix (but not necessarily other systems) have system level functions which can do this, but there's nothing in the standard which supports it. And if you ever end up having to remove bytes other than at the end, neither Windows nor Unix allow it (although some other systems do, at least in specific cases).


Why not truncate the file? Have a look at the chsize() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜