在c++17的环境下编写
写入文件中
#include<iostream>
#include<filesystem>
#include<fstream>
using namespace std;
namespace fs = std::filesystem;
int main() {
fs::path p{
"Mother's Day.txt" };//在此文件下定义.txt
ofstream output{
p };//定义输出文件的对象,并且赋值
output << "公历5月第2个周日是母亲节(Mother's Day)";//写入要输入的文本
output.close();//关闭文件输出流对象
cout << "size of " << p << " is" << fs::file_size(p) << endl;//输出文件大小
return (0);
}
读取文件
#include<iostream>
#include<filesystem>
#include<fstream>
using namespace std;
namespace fs = std::filesystem;
int main() {
fs::path p{
"Saying.txt" };
ifstream input{
p };
if (input.fail()) {
//判断文件是否可以成功打开
cout << "the file can't open" << endl;
}
//如果文件中有数字和字符串两种类型
string name;
int age;
input >> name >> age ;
cout << name <<" "<< age << endl;
/*
while (input.eof() == false) {//输出所有内容,直到末尾
cout << static_cast<char>(input.get());
}
*/
return (0);
}
fail()是类型不匹配时,返回true
bad()是文件受损时,返回true