C++之讀取和寫入文件


C++之讀取和寫入文件

在C++中使用std::ifstream來讀取文件, 使用std::ofstream來寫入文件,比如txt, yaml等文件。

讀取文件

#include <string>
#include <fstream>

std::string file_name;
std::ifstream file_reader(file_name);
if (file_reader.is_open())
{
  while (file_reader.peek() != EOF)
  {
  std::string line;
  std::getline(file_reader, line, '\n');
  // do something
  }
  file_reader.close();
}
else
{
std::cerr << "Fail to open file !" << std::endl;
}
  • 使用while(!file_reader.eof())判斷最后一行,該命令會把最后一行讀兩遍,所以使用while (file_reader.peek() != EOF)。

寫入文件

#include <string>
#include <fstream>

std::string file_name;
std::ofstream file_writer(file_name, std::ios_base::out)
file_writer << "AA" << "\t" << std::endl;
file_writer.close();

參考

C++ fstream流的eof()函數多讀一行的問題 - guoduhua的專欄 - CSDN博客
[c++ - Why does ifstream.eof() not return TRUE after reading the last line of a file? - Software Engineering Stack Exchange](


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM