0

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 ?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using SetEndOfFile for windows. I need to get with seek to the place I want to be end and then I use the method ? If I open it again and go to EOF it will be the new size ?
updated... see the link. it is written that you need to seek to the place where you want your EOF to be.
2

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).

7 Comments

I only need to do it in the end and not in the middle or beginning. My question is if I am using it in windows, will all other internal parameters of the OS will be updated for the change ?
If you're willing to use boost, 1.46 supports a resize() method now which should allow a degree of portability - why it wasn't included from the beginning is a mystery...
@Roman If you use the system dependent function, it will do what the system specifies it to do. If the system specifications say that it truncates the file, then it truncates the file (or there is a bug in the system).
Nothing in the standard to support truncating files?! Wow, that's an astounding omission.
@David It depends on your point of view. C and C++ are designed to be implementable on all platforms, and there are platforms which don't support truncation of files. (Early Unix didn't, and that's what C was originally developed on.)
|
1

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

3 Comments

I don't see it in the API of ifstream
it's not part of iostreams, it's a separate method which you call with the file - which will resize the file (and therefore remove the trailing bytes - which is presumably what you want?)
Using chsize for windows. If I open it again and go to EOF it will be the new size ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.