(一)、什么是文件:

文件是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位。文件的操作是基于文件,即文件的操作核心就是:读和写。也就是只要我们想要操作文件就是对操作系统发起请求,然后由操作系统将用户或应用程序对文件的读写操作转换成集体的硬盘指令(比如控制盘片转动,控制机械手臂移动,以此来读取数据)。
(二)、为什么要有文件
内存无法永久保存数据,但凡我们想要永久保存数据都需要把文件保存到硬盘中,而操作文件就可以实现对硬件的操作。
(三)、文件操作的三个步骤
ofstream (写文件),ifstream(读文件),frsream(读写操作)
(四)、I/O流的注意思想和简单思想

1.易混易迷点:
(1).要在E盘建立一个文件,在c++中E通e.
(2).输出流 ofstream,输入流ifstream(读取)
(3).打开文件,流对象.open()
(4).关闭文件,流对象.close().
(5).输入就是从磁盘上的文件中读取内容到内存中。并非cin【硬盘到内存】
(6).输出就是将内存中的数据内容输出或则说写入到磁盘的文件中。【内存到硬盘】
2.输出在文档上(但运行窗口不会有):
代码展示:
#include <iostream>
using namespace std;
#include <string>
#include <fstream>
int main()
{
string s1="123";
ofstream of; //定义输出流;
of.open("e:\\123.txt");
of << "输入的字符串是:"<<s1 << endl;
of.close();
return 0;
}
效果展示:

3.输入内存的操作
代码展示:
#include <iostream>
using namespace std;
#include <string>
#include <fstream>
int main()
{
string s1="2000";
ofstream of; //定义输出流;
ifstream If; //定义只读取文件;
of.open("e:\\123.txt");
of << "利用ofstream的字符串是:" << s1 << endl; //被读取的文件
of.close();
If.open("e:\\123.txt");
s1 = "888";
If >> s1; //读取文档123.txt到s1
cout<< "读取123.txt的文件是:" << s1 << endl;
return 0;
}
效果展示:

(五)、frstream对文件的综合管理
1.代码展示:
#include <iostream>
using namespace std;
#include <string>
#include <fstream>
int main()
{
string s1 = "41235";
fstream IO; //定义输入输出流的综合体;
IO.open("e:\\123.txt");
IO << "IO输出的字符串是:" << s1 << endl;
IO.close();
IO.open("e:\\123.txt");
s1 = "12354";
IO >> s1; //读取文档123.txt;
cout << "读取的文件是:" << s1 << endl;
IO.close();
return 0;
}
2.效果展示:


(六)、文件的打开

1.文件名
2.文件打开方式:

3.判断文件是否打开
3.1第一种方法:
代码展示:
#include <iostream>
using namespace std;
#include <string>
#include <fstream>
int main()
{
string s1="123";
ofstream of;
of.open("e:\\123.txt");
if (!of.is_open())
{
cout << "文件打开失败:" << endl;
}
cout << "文件打开成功!" << endl;
of << "输出到硬盘的数为::"<<s1 << endl;
of.close();
return 0;
}
效果展示:
