fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. void appendToFileWithFlush(const std::string& filePath, const std::string& content) {
  6. // 打开文件流
  7. std::ofstream outFile;
  8.  
  9. // 设置文件路径和模式
  10. outFile.open(filePath, std::ios::app);
  11.  
  12. // 检查文件是否成功打开
  13. if (!outFile.is_open()) {
  14. std::cerr << "无法打开文件:" << filePath << std::endl;
  15. return;
  16. }
  17.  
  18. // 写入内容
  19. outFile << content;
  20.  
  21. // 强制刷新缓冲区,确保数据立即写入文件
  22. outFile.flush();
  23.  
  24. // 关闭文件流
  25. outFile.close();
  26. }
  27.  
  28. int main() {
  29. std::string filePath = "example.txt"; // 文件路径
  30. std::string content = "这是追加的内容。\n"; // 要写入的内容
  31.  
  32. // 调用函数追加内容到文件
  33. appendToFileWithFlush(filePath, content);
  34.  
  35. std::cout << "内容已追加到文件:" << filePath << std::endl;
  36.  
  37. return 0;
  38. }
  39.  
  40.  
  41.  
Success #stdin #stdout #stderr 0.01s 5324KB
stdin
45
stdout
内容已追加到文件:example.txt
stderr
无法打开文件:example.txt