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

猜你喜欢

转载自www.cnblogs.com/ChrisCoder/p/9919656.html