给出完整的例子,说明c++文件如何覆盖写,追加写,等
时间: 2024-02-01 19:28:32 浏览: 72
下面是一个完整的例子,说明了C++中文件的覆盖写、追加写和截断写等操作:
```cpp
#include <iostream>
#include <fstream>
int main() {
// 覆盖写文件
std::ofstream outfile("file.txt"); // 创建输出文件流对象,并打开文件
if (outfile.is_open()) {
outfile << "This is line 1." << std::endl; // 写入第一行
outfile << "This is line 2." << std::endl; // 写入第二行
outfile.close(); // 关闭文件
} else {
std::cerr << "Failed to open the file." << std::endl;
}
// 追加写文件
std::ofstream appendFile("file.txt", std::ios::app); // 创建输出文件流对象,并以追加模式打开文件
if (appendFile.is_open()) {
appendFile << "This is a new line." << std::endl; // 追加写入新行
appendFile.close(); // 关闭文件
} else {
std::cerr << "Failed to open the file." << std::endl;
}
// 截断写文件
std::ofstream truncateFile("file.txt", std::ios::trunc); // 创建输出文件流对象,并以截断模式打开文件
if (truncateFile.is_open()) {
truncateFile << "This is a truncated line." << std::endl; // 截断写入新行
truncateFile.close(); // 关闭文件
} else {
std::cerr << "Failed to open the file." << std::endl;
}
// 读取文件内容
std::ifstream infile("file.txt"); // 创建输入文件流对象,并打开文件
if (infile.is_open()) {
std::string line;
while (std::getline(infile, line)) { // 逐行读取文件内容
std::cout << line << std::endl; // 输出读取的内容
}
infile.close(); // 关闭文件
} else {
std::cerr << "Failed to open the file." << std::endl;
}
return 0;
}
```
上述代码首先使用`std::ofstream`对象创建输出文件流对象,并打开名为"file.txt"的文件。然后,使用`<<`运算符将内容写入文件中,实现覆盖写操作。关闭文件后,代码使用`std::ios::app`选项重新打开文件,实现追加写操作。再次关闭文件后,使用`std::ios::trunc`选项重新打开文件,实现截断写操作。最后,使用`std::ifstream`对象创建输入文件流对象,逐行读取文件内容,并输出到控制台。
运行上述代码后,"file.txt"文件的内容将被覆盖写、追加写和截断写,然后读取并输出到控制台。这个例子展示了C++中文件的不同写入模式和读取操作。