本文为学习文件管理的笔记.
#include<iostream> //理论上<fstream>包括<iostream>,但在VS 2017上若无此句,cin/cout标识符将无法识别
#include<fstream>
using namespace std;
int main()//将数据写入文件
{
int a[10];
fstream f1; //建立 fstream类的一个对象
f1.open("t1.txt",ios::app|ios::in); //用对象的open()函数 文件操作
for (int i = 0; i < 10; i++){
cin >> a[i]; //键盘>>内存
f1 << a[i] << "\n"; //内存>>文件
}
f1.close();
system("pause");
return 0;
}
文件如下:
2. //从文件读数据
#include<iostream>
#include<fstream>
using namespace std;
int main()//从文件读数据
{
int a[10];
fstream f1;
f1.open("t1.txt",ios::out|ios::in);
for (int i = 0; i < 10; i++){
/*关键*/ f1 >> a[i];
cout << a[i]<<endl;
}
f1.close();
system("pause");
return 0;