gpt4 book ai didi

Opening an existing text file erases its contents altogether(打开现有文本文件会完全删除其内容)

翻译 作者:bug小助手 更新时间:2023-10-26 21:49:54 24 4
gpt4 key购买 nike



I am trying to open a text file (it has content). Every time I open it, the content of the file ends up being erased altogether, which I do not want.

我正在尝试打开一个文本文件(它包含内容)。每次我打开它,文件的内容都会被完全删除,这是我不想要的。


#include <fstream>
#include <iostream>

using namespace std;

int main() {
string filename;
cout << "Enter File name : ";
cin >> filename;
fstream file;
file.open(filename, fstream::out);
file.close();
return 0;
}

更多回答

Usually you want std::ios::in | std::ios::out. std::ios::app only allows you to write to the end of the file--even if you seek to somewhere else in the file, any attempt at writing will seek to the end first, then do the writing. That's good for things like log files; not so good for most others.

通常你需要std::ios::in| std::initializer std::ios::app只允许你写到文件的末尾--即使你在文件中寻找其他地方,任何写的尝试都会先寻找到末尾,然后再写。这对日志文件之类的东西很好,但对大多数其他东西就不那么好了。

This doesn’t address the question, but get in the habit of creating objects with meaningful values rather than default initializing them and immediately overwriting the default value. In this case that means changing fstream file; file.open(filename, fstream::out); to fstream file(filename, fstream::out);. Also, you don’t need to call file.close();. The destructor will do that.

这并没有解决这个问题,而是养成了用有意义的值而不是缺省值创建对象的习惯,初始化它们并立即覆盖缺省值。在本例中,这意味着将fstream文件;file.open(文件名,fstream::out);更改为fstream文件(文件名,fstream::out);。此外,您也不需要调用file.Close();。析构函数会这么做的。

Does this answer your question? fstream file being rewritten

这回答了你的问题吗?正在重写fstream文件

优秀答案推荐

Instead of fstream::out which discards everything which was previously present in the file, you should use fstream::app which will not delete the contents of the file and continue writing to it from its end.

您应该使用fstream::app,而不是fstream::out,它会丢弃文件中以前存在的所有内容,它不会删除文件的内容,并从文件末尾继续写入内容。




From cppreference:

来自cp首选项:








































Constant Explanation
app seek to the end of stream before each write
binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open
noreplace (C++23) open in exclusive mode

更多回答

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com