读写文件
#include <fstream>
#include <iostream>
#include <string>
#include <unistd.h> //使用access和F_OK
int main()
{
//读文件
std::string ifile_name= "test.txt";
if (access(ifile_name.c_str(), F_OK) == -1) //判断文件是否存在
{
std::cout << "file not exists: " << ifile_name << std::endl;
}
else
{
std::ifstream infile(ifile_name, std::ios::in); //打开读文件, 使用ifstream
std::string line;
while(std::getline(infile, line)) //获取每一行内容, 放到变量line中.
{
std::cout << line << std::endl;
}
infile.close(); //关闭文件
}
//写文件
std::string ofile_name= "test.txt.out";
std::ofstream outfile;
outfile.open(ofile_name); //打开写文件, 使用ofstream
outfile << "line0" << std::endl; //写入内容
outfile << "line1" << std::endl;
outfile << "line2" << std::endl;
outfile.close(); //关闭
return 0;
}