Dod*_*ion 7 c++ fstream visual-studio-2012
这个app
问题询问和之间的区别,ate
答案和cppreference都暗示唯一的区别是,这app
意味着在每次写操作之前将写游标放在文件的末尾,而意味着ate
将写游标放在文件的末尾仅在打开时才显示该文件。
我实际上看到的(在 VS 2012 中)是指定ate
丢弃现有文件的内容,而app
不会(它将新内容附加到以前存在的内容)。换句话说,ate
似乎是在暗示trunc
。
以下语句将“Hello”附加到现有文件中:
ofstream("trace.log", ios_base::out|ios_base::app) << "Hello\n";
Run Code Online (Sandbox Code Playgroud)
但以下语句将文件的内容替换为“Hello”:
ofstream("trace.log", ios_base::out|ios_base::ate) << "Hello\n";
Run Code Online (Sandbox Code Playgroud)
VS 6.0 的 MSDN 文档暗示这种情况不应该发生(但这句话似乎在 Visual Studio 的更高版本中已被撤回):
ios::trunc:如果文件已经存在,则其内容将被丢弃。如果指定了 ios::out,并且未指定 ios::ate、ios::app 和 ios:in,则隐含此模式。
您需要结合std::ios::in
然后std::ios::ate
查找文件末尾并附加文本:
假设我有一个文件“data.txt”,其中包含以下行:
"Hello there how are you today? Ok fine thanx. you?"
Run Code Online (Sandbox Code Playgroud)
现在我打开它:
1:std::ios::应用程序:
std::ofstream out("data.txt", std::ios::app);
out.seekp(10); // I want to move the write pointer to position 10
out << "This line will be appended to the end of the file";
out.close();
Run Code Online (Sandbox Code Playgroud)
结果不是我想要的:没有移动写入指针,但只有文本始终附加到末尾。
2:std::ios::ate:
std::ofstream out2("data.txt", std::ios::ate);
out2 << "This line will be ate to the end of the file";
out2.close();
Run Code Online (Sandbox Code Playgroud)
上面的结果不是我想要的,没有附加文字,但内容被截断了!
要解决它,请ate
结合in
:
std::ofstream out2("data.txt", std::ios::ate | std::ios::in);
out2 << "This line will be ate to the end of the file";
out2.close();
Run Code Online (Sandbox Code Playgroud)
现在文本已附加到末尾,但有什么区别:
正如我所说,应用程序不允许移动写入指针,但 ate 可以。
std::ofstream out2("data.txt", std::ios::ate | std::ios::in);
out2.seekp(5, std::ios::end); // add the content after the end with 5 positions.
out2 << "This line will be ate to the end of the file";
out2.close();
Run Code Online (Sandbox Code Playgroud)
上面我们可以将写入指针移动到我们想要的位置,而使用 app 则不能。
归档时间: |
|
查看次数: |
12081 次 |
最近记录: |