Triumphant
Triumphant

Reputation: 958

what's the difference between ios_base::ate and ios_base::trunc?

Here is the documents from MSDN: ate, to seek to the end of a stream when its controlling object is first created.

trunc, to delete contents of an existing file when its controlling object is created.

I just can't understand the differences between them, the following two code snippet behave the same(they clear the contents before doing insert), anyone can help me find out the differences?

code snippet 1:

ofstream ofs(L"F:\\iMoney.txt", ios_base::trunc);
ofs << L"Hello, money~" << endl;
ofs.close();

code snippet 2:

ofstream ofs(L"F:\\iMoney.txt", ios_base::ate);
ofs << L"Hello, money~" << endl;
ofs.close();

Upvotes: 1

Views: 836

Answers (2)

David G
David G

Reputation: 96810

Your example doesn't make much of a difference if the file is empty or new, but if the file already contained characters then opening with std::ios_base::ate and writing to the file will append characters while writing after opening with std::ios_base::trunc will overwrite those characters.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490178

For std::ate to make real sense, you need to open an fstream for both reading and writing:

std::fstream file("iMoney.txt", std::ios::in | std::ios::out | std::ios::ate);

This will preserve existing content, and the write position will start out at the end of the file, so what you write will be appended to the existing content unless you use seekp to move the write position somewhere else.

By contrast, if you specify std::ios::trunc, all existing content will be removed from the file (regardless of specifying std::ios::in, std::ios::out, or both). But if you just specify std::ios::out, which the default for an std::ofstream) all the existing content will be removed anyway. The only time std::ios::trunc adds anything useful is what you also specify both in and out, in which case the existing content would be preserved if you didn't specify std::ios::trunc.

Upvotes: 2

Related Questions