ofstream 写入文件不覆盖
时间: 2023-09-22 21:11:28 浏览: 78
在使用 ofstream 写入文件时,如果不想覆盖原有文件内容,可以使用以下方法:
1. 使用 ios::app 模式打开文件,即在文件末尾追加内容。
```cpp
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("example.txt", ios::app);
outfile << "This is some additional text." << endl;
outfile.close();
return 0;
}
```
2. 使用 ios::in 模式打开文件,即在文件原有内容上继续写入。
```cpp
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("example.txt", ios::in);
outfile.seekp(0, ios::end);
outfile << "This is some additional text." << endl;
outfile.close();
return 0;
}
```
其中,outfile.seekp(0, ios::end) 表示将文件指针移动到文件末尾。
相关问题
c++ 覆盖写入文件
在C++中,你可以使用`ofstream`类来覆盖写入文件。以下是一个简单的示例代码,演示如何覆盖写入文件:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ofstream outputFile("example.txt"); // 打开一个名为 example.txt 的文件
if (outputFile.is_open()) {
outputFile << "This text will be overwritten." << std::endl; // 覆盖写入文本
outputFile.close(); // 关闭文件
std::cout << "文件覆盖写入成功!" << std::endl;
}
else {
std::cout << "无法打开文件!" << std::endl;
}
return 0;
}
```
在上面的示例中,我们首先创建一个`ofstream`对象命名为`outputFile`,并传入文件名`example.txt`作为参数来打开或创建一个文件。然后,我们使用`<<`运算符将要覆盖写入的文本写入到文件中。由于默认情况下,`ofstream`对象以覆盖模式打开文件,所以之前存在的内容将被覆盖。最后,使用`close()`方法关闭文件。
如果文件成功打开,并且覆盖写入操作成功,我们将会看到输出提示"文件覆盖写入成功!"。如果无法打开文件,将会显示"无法打开文件!"。
当然,你可以根据需要进行更复杂的覆盖写入操作,例如覆盖写入多行文本或二进制数据。这只是一个简单的示例来演示基本的覆盖写入文件操作。
cpp文件流写入时不覆盖原有数据
如果你希望在写入文件时不覆盖原有数据,可以使用文件流的 append 模式。在打开文件时,将文件打开模式设置为 `ios::app`,这样写入文件时就会在文件末尾添加新数据,而不会覆盖原有数据。
示例代码如下:
```cpp
#include <fstream>
#include <iostream>
int main() {
std::ofstream outfile;
outfile.open("example.txt", std::ios::app);
if (!outfile.is_open()) {
std::cerr << "Failed to open file!" << std::endl;
return 1;
}
outfile << "New data" << std::endl;
outfile.close();
return 0;
}
```
在上面的示例中,我们打开了一个名为 example.txt 的文件,设置了文件打开模式为 `ios::app`,然后向文件中写入了一些新数据。这些新数据会被添加到文件末尾,而不会覆盖原有数据。