一、从文件读数据
//std::c++ latest
#include<iostream>
#include<fstream>
#include<filesystem>
#include<string>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
using std::string;
namespace fs = std::filesystem;
int main()
{
fs::path p{ "E:\\C_pp\\hello.txt" };
ifstream input{ p };
if (input.fail())
{
cout << "Can't open file " << p << endl;
std::cin.get();
return 0;
}
string name{ " " };
double score{ 0.0 };
//已知格式读取信息
input >> name >> score;
cout << name << " " << score << endl;
input >> name >> score;
cout << name << " " << score << endl;
//未知格式 读取全部信息
//char x;
//while (!input.get(x).eof())
//{
// cout << x;
//}
std::cin.get();
return 0;
}
结果如上图所示。
二、向文件写数据
//std::c++ latest
#include<iostream>
#include<fstream>
#include<filesystem>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
namespace fs = std::filesystem;
int main()
{
fs::path p{ "E:\\C_pp\\hello.txt" };
ofstream output{ p };
double lileiScore{ 90.5 };
int hanmeimeiScore{ 84 };
output << "Lilei " << lileiScore << endl;
output << "HanMeimei" << hanmeimeiScore << endl;
output.close();
cout << "size of " << p << "is " << fs::file_size(p) << endl;
std::cin.get();
return 0;
}
结果如上图所示。