C++:写入现有文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4186547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: Write to an existing file?
提问by olidev
In C++, I need to write to an existing file and keep the previous content there.
在 C++ 中,我需要写入现有文件并将以前的内容保留在那里。
This is what I have done:
这就是我所做的:
std::ofstream logging;
logging.open(FILENAME);
logging << "HELLO\n";
logging.close();
but then my previous text is overwritten (gone). What did I do wrong?
但后来我以前的文字被覆盖(消失)。我做错了什么?
Thanks in advance.
提前致谢。
回答by Alexey Malistov
logging.open(FILENAME, std::ios_base::app);
回答by Drew Frezell
You have to open the file in append mode:
您必须以追加模式打开文件:
logging.open(FILENAME, std::ios::app);
回答by luke
By default the "opening mode" for a file is overwrite. Try opening the file in append mode
默认情况下,文件的“打开模式”会被覆盖。尝试以追加模式打开文件
The second parameter of open
is an enum bitflag. The two options you should check out are:
的第二个参数open
是一个枚举位标志。您应该检查的两个选项是:
- app - seek to the file end before each write
ate - seek to the file end after open
logging.open(FILENAME, std::ios::app|std::ate);
- app - 在每次写入之前寻找文件结尾
ate - 打开后寻找文件末尾
logging.open(文件名,std::ios::app|std::ate);
回答by Sanja Melnichuk
do you try ? something like that
你试试?类似的东西
myFile.open( "file.txt", ios::out | ios::app );