C++ std::string 变量写入文件:追加内容而非覆盖
{"title":"C++ std::string 变量写入文件:追加内容而非覆盖","description":"本文讲解如何使用 C++ 中的 std::ofstream 类以追加模式写入文件,避免使用 fputs 函数覆盖原有内容,确保每次运行程序时新的内容都会被追加到文件末尾。","keywords":"C++, std::string, fputs, ofstream, 文件写入, 追加模式, 覆盖, 文件操作","content":"要避免清除txt文件原有内容被覆盖掉,可以使用ofstream来打开文件并写入内容。而不是使用fputs函数。\n\n示例代码:\n\ncpp\n#include <iostream>\n#include <fstream>\n\nint main() {\n std::ofstream file("example.txt", std::ios::app); // 以追加模式打开文件\n if (file.is_open()) {\n std::string text = "Hello, World!";\n file << text; // 写入内容\n file.close(); // 关闭文件\n } else {\n std::cout << "无法打开文件" << std::endl;\n }\n\n return 0;\n}\n\n\n这样,每次运行程序时,新的内容都会被追加到文件末尾,而不会覆盖掉原有内容。"}
原文地址: https://www.cveoy.top/t/topic/p3Hd 著作权归作者所有。请勿转载和采集!