一、基本语法
- 文件操作头文件需要包含<fstream>
- 文件类型分为两种:文本文件:
文件以ASCII码形式存储于计算机中;二进制文件:文件以文本的二进制形式存储于计算机中,用户一般不能直接读懂它们
- 操作文件的三大类:
1)ofstream:写操作 2)ifstream:读操作 3)fstream:读写操作
写文件的五步:
1)包含头文件:#include<fstream>
2)创建流对象:ofstream ofs;
3)打开文件:ofs.open(”文件路径”,打开方式)
4)写数据:ofs<<"写入数据”;
5)关闭文件:ofs.close();
注意:文件打开方式可以配合使用,利用|操作符。如,用二进制方式写文件:ios::binary|ios::out
二、代码练习
1、写文件
#include<iostream>
using namespace std;
#include<fstream>
//文本文件 写文件
void test01()
{
//1、包含头文件fstream
//2、创建流对象
ofstream ofs;
//3、打开文件路径
ofs.open("D:\\C++\\c++class\\第二部分\\file\\text.txt", ios::out);
//4、写入内容
ofs << "Hello World" << endl;
ofs << "Susan" << endl;
ofs << "18岁" << endl;
//5、关闭文件
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
2、读文件
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
//文本文件 读文件
void test01()
{
//1、包含头文件fstream
//2、创建流对象
ifstream ifs;
//3、打开文件路径,判断是否打开成功
ifs.open("D:\\C++\\c++class\\第二部分\\file\\text.txt", ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//4、写入内容
//方法一
//char buf[1024] = { 0 };//全为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 c;
while ((c = ifs.get()) != EOF)//EOF end if file
{
cout << c;
}
//5、关闭文件
ifs.close();
}
int main()
{
test01();
system("pause");
return 0;
}