c++对文件操作需要包含头文件<fstream>
文件类型分为两种:
1.文本文件:ASCII的形式储存在计算机中
2.二进制文件:以二进制储存在计算机中
操作文件的三大类
1.ofstream:写
2.ifstream:读
3.fstream :读
#include <iostream>
using namespace std;
#include <fstream>
#include <string>
//1.包含头文件
#include <fstream>
//2.创建流对象
//ofstream ofs;
//3.打开文件
//ofs.open("文件路径", "打开方式");
//4.写文件
//ofs << "写入的数据";
//5.关闭文件
//ofs.close();
//文件打开方式:
//ios::in 为读文件读文件
//ios::out 为写文件打开文件
//ios::ate 初始位置文件尾;
//ios::app 追加方式写文件
//ios::trunc 先删除,再创建
//iso::binary 二进制方式
//文件读写方式可以配合使用,利用|操作符
//例如:用二进制方式写文件 ios::binary | iso::out
void test01()
{
//包含头文件
//2.创建对象流
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
//5.关闭文件
ofs.close();
}
void test02()
{
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件并判断
ifs.open("test.txt", ios::in);
if( !ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//4.读数据
//4.1
//char buf[1024] = { 0 };
//while (ifs >> buf)
//{
// cout << buf << endl;
//};
4.2
//char buf[1024] = { 0 };
//while(ifs.getline(buf,sizeof(buf)))
//{
// cout << buf << endl;
//}
//4.3
string buf;
while(getline(ifs,buf))
{
cout << buf << endl;
}
//4.4
char c;
while((c=ifs.get()) != EOF)
{
cout << c;
}
//5.关闭文件
ifs.close();
}
int main()
{
test02();
system("pause");
return 0;
}