C++文件读取

1.1头文件

需要包含头文件#include “fstream”

1.2读写文件概括

写入文件:创建ofstream对象,使用ofstream方法,如 << 和 write()
读取文件:创建ifstrean对象,使用ifstream方法,如 >> 和 get()

2.1写入文件

创建ofstream对象,使用调用open()打开文件,使用 << 方式写入文件
也可以调用构造函数,不调用open()方法

int main(){
	ofstream fout;
	fout.open("新建文本文档.txt");
	ofstream fout("新建文本文档.txt");
	fout << "hello world";
	fout.close();//显示关闭输出流
	return 0;
}

这里的写入文件原则是:该文件存在,新内容将覆盖旧内容
该文件不存在,直接创建该文件(同程序源代码处于一个文件下)
ostream是ofstream的基类,因此可以使用ostream里的所有方法包括:插入运算符定义、格式化方法、控制符
ofstream使用缓冲输出的方法,举个例子,创建两个ofstream对象,程序便会创建两个缓冲区
缓冲的优点:提高程序写入速度

2.2读取文件

读取文件同写入文件相似

int main(){
	ifstream fin;
	//ifstream fin("新建文本文档.txt");
	fin.open("新建文本文档.txt");
	char ch;
	while(fin.get(ch)){
		cout << ch;
	}
	fin.close();//显示关闭输入流
	return 0;
}

close()方法不会删除流,只是断开流的链接(流仍会被保留)

2.3读写文件应用

int main(){
	string filename;
	cin >> filename;//输入文件名
	//ofstream fout(filename.c_str());
	ofstream fout;
	fout.open(filename.c_str());//创建文本文件,c_str()提供c风格字符串
	fout << "0001, zhangsan, 19, 100\n";
	fout << "0002, wangwu, 18, 99";
	fout.close();
	//ifstream fin(filename.c_str());
	ifstream fin;
	fin.open(filename.c_str());
	char ch;
	while(fin.get(ch)){
		cout << ch;
	}
	fin.close();
	return 0;
}

也可以使用构造函数省略open()操作

3.1流状态检查

进行文件操作前先使用is_open()进行检查

if(fin.is_open()){

}

3.2打开多个文件

int main(){
	ifstream fin;
	fin.open("test.txt");
	char ch;
	while(fin.get(ch)){
		cout << ch;
	}
	cout << endl;
	fin.close();
	fin.clear();
	fin.open("test2.txt");
	while(fin.get(ch)){
		cout << ch;
	}
	fin.close();
	return 0;
}

使用同一个流处理文件,减少占用计算机资源,提高效率

3.3文件模式

fstream finout;
finout.open("test.txt", ios::in | ios::out | ios::binary);
常量含义
ios_base::in打开文件,以便读入
ios_base::out打开文件,以便写入
ios_base::ate打开文件,并移到文件尾
ios_base::app追加到文件尾
ios_base::trunc如果文件存在,则截断文件
ios_base::binary二进制文件

4.1其他概念

流:进出程序的字节流
缓冲区:内存的临时存储区
seekg():将输入指针移到指定位置
seekp():将输出指针移到指定位置
tellg()、tellp():报告文件当前位置

4.2应用

统计单词在文本文件中出现次数和行号

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值