基本指令
写文件时,文件打开模式:
ios::out, (output)
覆盖写入模式, 清空原有内容,从头写入新内容
ios::app, (append)
追加写入模式, 保留原有内容,尾部写入新内容 ,如果文件存在,就打开文件,否则,如果文件不存在,则创建并打开一个空白文件
读文件时,文件打开模式:
ios::in, (input)
以只读方式直接打开文件 ,只能读取,不能写入
简单应用
下面以例题解释应用
输入n个整数,保存到data.txt文件中,然后从data.txt文件读取数据,并返回所有数据的和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include<iostream> #include<fstream> using namespace std; int main() { char filename[20]="data.txt"; ofstream output(filename,ios::out); if(!output) { cout<<"Fail to open the file"<<endl; } else { int n,a; cin>>n; for(int i=0;i<n;i++) { cin>>a; output<<a<<" "; } } output.close(); ifstream input(filename,ios::in); int sum=0; char str[200]; if(!input) { cout<<"Fail to open the file"<<endl; } else { int b; while(input>>b) { sum+=b; }
} input.close(); cout<<sum; return 0; }
|