文件的创建与读取 文件的数据添加
一:概要
1:首先要站在程序的角度上。
2:文件的创建 即将程序中的数据 写入到文件当中。
3:文件的读取 即将一个文件中的信息读取到程序当中。
二:步骤
1:创建文件流
2:打开文件流
3:往文件中写入数据
4:关闭文件流
注意:第一步和第二步可以合并为一步 即:ofstream ofile("num.txt",ios::out);
三:上代码
1:文件的创建:
#include<bits/stdc++.h>
using namespace std;//先创建一个文件 然后往文件里写东西
int main()
{int a[5] = { 1,2,3,4,5};//创建文件;ofstream ofile; //ofstream ofile("num.txt",ios::out); //打开文件ofile.open("num.txt",ios::out); if( ofile == NULL){cout << "open fail" << endl;exit(1);}//向文件中写入数据for( int i = 0; i < 5; i++ ){ofile << a[i] << ' '; } //关闭流文件ofile.close();
}
2:文件的读取(将一个文件中的数据读入到代码当中)
#include<bits/stdc++.h>
using namespace std;int main()
{int b[5];//创建文件 ifstream ifile;//打开文件ifile.open("num.txt", ios::in);//从程序的角度出发 读入一个文件if( ifile == NULL){cout << "fail" << endl;exit(1); }for( int i = 0; i < 5; i++ ){ifile >> b[i]; }ifile.close();for( int i = 0; i < 5; i++ ){cout << b[i] << ' '; }
}
3:在一个文件中的内容已有的情况下 存入数据
#include<bits/stdc++.h>
using namespace std;int main()
{int a[5] = { 1,2,3,4,5};//创建文件;ofstream ofile; //ofstream ofile("num.txt",ios::out); //打开文件ofile.open("num.txt",ios::out); if( ofile == NULL){cout << "open fail" << endl;exit(1);}//向文件中写入数据for( int i = 0; i < 5; i++ ){ofile << a[i] << ' '; } //关闭流文件ofile.close();int temp = 100;ofile.open("num.txt",ios::app);ofile << ' ' << temp;ofile.close();
}