#include<iostream>
#include <fstream> //头文件引用
using namespace std;
//输出到缓冲区(写文件)
void test01()
{
//流对象 参数 1 文件路径 2 打开方式
//ofstream ofs("./test.txt", ios::out | ios::trunc);
ofstream ofs;
ofs.open("./test.txt", ios::out | ios::trunc); //指定打开方式
//判断是否打开成功
if ( ! ofs.is_open() )
{
cout << "文件打开失败" << endl;
}
ofs << "姓名:德玛" << endl;
ofs << "年龄:18" << endl;
ofs << "身高:165cm" << endl;
ofs.close(); //关闭流对象,更新缓冲区
}
//输入到缓冲区(读文件)
void test02()
{
ifstream ifs;
ifs.open("./test.txt",ios::in); //读文件
if (ifs.is_open() == false)//可以这样写if(!ifs)
{
cout << "文件打开失败" << endl;
}
//第一种方式读文件
//char buf[1024] = {0};
////每次都读1行数据,并且放到buf中
//while (ifs >> buf)//肯定重载了>>运算符
//{
// cout << buf << endl;
//}
//第二种方式
//char buf[1024] = { 0 };
//while (!ifs.eof()) //判断是否读到文件的尾部
//{
// ifs.getline(buf, sizeof(buf));
// cout << buf << endl;
//}
//第三种方式 单个字符读取
// ifs.get() 以单个字符读取文件
char c;
while ((c = ifs.get()) != EOF)
{
cout << c;
}
//关闭文件对象
ifs.close();
}
int main(){
test01();//运行test01后在相应的目录中能找到test.txt文件
test02();//要保证相应的目录中有test.txt文件
system("pause");
return EXIT_SUCCESS;
}