文件输入输出,可用于参数的传入,结果的输出
共包含五步
1.包含头文件
2.创建流对象
3.打开文件 流对象.open(文件名 , 打开方式)
4.写/读 << getline() write() read()
5.关闭文件 流对象.close
#include<iostream>
//包含头文件
#include<fstream>
#include<string>
using namespace std;
void test_write();
void test_read();
void binarytest_write();
void binarytest_read();
int main() {
//test_write();
//test_read();
//binarytest_write();
binarytest_read();
return 0;
}
void test_write()
{
ofstream ofs;
//打开方式,out:代表为写文件而打开
ofs.open("text.txt",ios::out);
//写文件
ofs << "姓名:张三" << endl;
ofs << "姓别:男" << endl;
ofs << "年龄:18" << endl;
//关闭文件
ofs.close();
}
void test_read()
{
//创建流对象
ifstream ifs;
//打开
ifs.open("text.txt", ios::in);
if (!ifs.is_open())
{
cout << "file opens failed" << endl;
return;
}
//读文件
方法一
读文件
//char buf[1024] = { 0 };
传入时 会以空格和换行为界限
//while (ifs >> buf)
//{
// cout << buf << endl;
//}
//方法二
char buf[1024] = { 0 };
//以换行为界限
while (ifs.getline(buf,sizeof(buf)))
{
cout << buf << endl;
}
方法三
//string buf;
以换行为界限
//while (getline(ifs,buf))
//{
// cout << buf << endl;
//}
//方法四
//char f;
//逐字符读取
//while ((f = ifs.get()) != EOF)
//{
// cout << f;
//}
//关闭文件
ifs.close();
}
class Person
{
public:
char m_name[64];
int m_age;
};
void binarytest_write()
{
//创建输出流对象
ofstream ofs;
//打开文件,二进制方式写
ofs.open("person.txt",ofs.out| ofs.binary);
//写文件
Person p = { "张三", 18 };
ofs.write((const char*)&p,sizeof(p));
//关闭文件
ofs.close();
}
void binarytest_read()
{
//创建输入流对象
ifstream ifs;
//打开文件,二进制方式读
ifs.open("person.txt", ifs.in | ifs.binary);
if(!ifs.is_open())
{
cout << "file opens failed" << endl;
return;
}
Person p;
ifs.read((char*)&p,sizeof(p));
cout << "姓名:" << p.m_name << endl;
cout<<"年龄:" << p.m_age << endl;
}