0%

C++文件操作

基本指令

写文件时,文件打开模式:

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;
}
/*
while(input.get(b))//逐字符读取(包含所有分隔符:空格/制表符/换行符)
{
cout<<b<<endl;
}
*/
/*方式二:逐单词读取
while( fin >> str )
{
cout << str << endl;
}
*/
/*方式三:逐行读取
while( fin.getline(str, 200) )
{
cout << str << endl;
}
*/
}
input.close();//关闭文件
cout<<sum;
return 0;
}