I would like to use either fstream
or preferably QFile
to remove the contents of a file after a specific position (that's not the beginning or the end of the file). So I first jump to that position with QFile::seek(long)
or equivalent in constant time, and then I would like to remove the remainder of the content, also in constant time. What approach do you recommend?
Asked
Active
Viewed 4,002 times
3

Community
- 1
- 1

Alan Turing
- 12,223
- 16
- 74
- 116
3 Answers
10
You can use QFile::resize
to resize the file to the size you want. I bet it uses truncate
behind the scenes (see Andrew's post).

C. K. Young
- 219,335
- 46
- 382
- 435
3
Lookup...
#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);
A quick snip from this site yielded...
If the file previously was larger than length, the extra data is discarded.
You may also find this answer interesting.

Community
- 1
- 1

Andrew White
- 52,720
- 19
- 113
- 137
-
Your answer is technically correct (and what I thought about writing at first), but the OP asked for a `QFile`-based solution. Thankfully, there is one. – C. K. Young May 30 '11 at 01:24
-
Fair enough, I knew this would work so I included it. I also didn't know resize used truncate so you'll get a +1 for me. I'll also leave this answer since it is valid though not optimal. – Andrew White May 30 '11 at 01:26
-
Great answer, but yes, the `QFile::resize` answer does address what I was looking for. Thank you! +1 – Alan Turing May 30 '11 at 01:35
0
Consider the new position, after the seek()
, to be the end of the file. When you're done working with the file write everything from the start up until that point.

wilhelmtell
- 57,473
- 20
- 96
- 131