在C++中,使用标准库中的std::fstream类可以进行文件操作,包括文件的读取和写入。下面是一些常见的文件写入模式及其介绍:
文件写入模式
-  std::ofstream (Output File Stream) - 专门用于文件写入的流。
- 默认模式下,如果文件不存在,会创建一个新的文件;如果文件存在,会清空文件内容再写入。
 std::ofstream ofs("example.txt"); ofs << "Hello, World!"; ofs.close();
-  std::fstream (File Stream) - 既可以用于文件读取,也可以用于文件写入。
- 需要指定适当的模式来进行写入操作。
 
常见的文件打开模式
std::fstream和std::ofstream的构造函数和open方法可以接受一个模式参数,用来指定如何打开文件。常见的模式包括:
-  std::ios::out - 打开文件用于写入。如果文件不存在,会创建一个新文件;如果文件存在,会清空文件内容。
 std::ofstream ofs("example.txt", std::ios::out);
-  std::ios::app (Append) - 以追加模式打开文件。写入的数据会被追加到文件末尾,不会清空文件。
 std::ofstream ofs("example.txt", std::ios::app);
-  std::ios::ate (At End) - 打开文件后,将文件指针移动到文件末尾。虽然文件指针在末尾,但文件内容不会被清空,可以在任意位置写入。
 std::ofstream ofs("example.txt", std::ios::ate);
-  std::ios::trunc (Truncate) - 如果文件存在,将清空文件内容。如果文件不存在,会创建一个新文件。这个模式是std::ios::out的默认行为。
 std::ofstream ofs("example.txt", std::ios::trunc);
- 如果文件存在,将清空文件内容。如果文件不存在,会创建一个新文件。这个模式是
-  std::ios::binary (Binary Mode) - 以二进制模式打开文件。读写操作以二进制方式进行,不进行任何格式化处理。
 std::ofstream ofs("example.txt", std::ios::binary);
组合使用模式
可以组合多个模式一起使用,通过按位或运算符 | 来组合:
std::ofstream ofs("example.txt", std::ios::out | std::ios::app);
例子
-  以写入模式打开文件: std::ofstream ofs("example.txt", std::ios::out); if (ofs.is_open()) {ofs << "Hello, World!";ofs.close(); }
-  以追加模式打开文件: std::ofstream ofs("example.txt", std::ios::app); if (ofs.is_open()) {ofs << "Appending this line.";ofs.close(); }
-  以二进制模式打开文件: std::ofstream ofs("example.bin", std::ios::out | std::ios::binary); if (ofs.is_open()) {int num = 100;ofs.write(reinterpret_cast<const char*>(&num), sizeof(num));ofs.close(); }
总结
- std::ofstream和- std::fstream类用于文件写入,前者专用于写入,后者可用于读写。
- 打开文件时可以指定不同的模式,如std::ios::out、std::ios::app、std::ios::ate、std::ios::trunc和std::ios::binary,根据需求选择合适的模式。
- 多个模式可以通过|组合使用。
理解这些模式和如何组合使用它们,可以帮助你更灵活和高效地进行文件操作。