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