Let's say I'm writing to a file a series of integers like this:
4
3
2
1
0

After writing the last number (or the last line), can I delete that last one?

Dani AI

Generated

A few practical options, building on comments already in the thread by and .

If you can avoid writing the extra line, that is simplest. If you need to remove a line after writing, there are two common approaches: rewrite to a new file (the safe, portable method that suggested), or truncate the existing file to a smaller byte length.

The cleanest portable truncation in modern C++ is std::filesystem::resize_file (C++17). Typical steps: write (in binary mode so newline bytes are predictable), keep the number of bytes you just wrote (or compute the last-line byte length), flush, capture the output position with tellp, close the stream, then call resize_file to shorten the file. See the reference for resize_file and tellp for details (resize_file, tellp).

Example outline (conceptual):

write last_bytes to file (open with std::ios::binary);
out.flush();
auto pos = out.tellp();
out.close();
std::filesystem::resize_file(path, pos - last_bytes.size());

If using OS APIs directly, POSIX offers ftruncate and Windows has SetEndOfFile — both remove bytes from the end of a file (ftruncate, SetEndOfFile). Those require a file descriptor/handle and care with text-mode newline translation. If you do not know the last-line length, open the file in binary and scan backward to the previous newline, then truncate there.

Note: truncation is not atomic across readers — for safe atomic updates prefer the temp-file-and-rename pattern.

Recommended Answers

All 3 Replies

Do not write the line in the first place and you do not have to delete it. :)

Do not write the line in the first place and you do not have to delete it. :)

But I really wanna know how to delete the last line!:twisted:

But I really wanna know how to delete the last line!

Then make a new file, copy only the content you need from the first one, delete the first file, and rename the second file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.