07_C++文件读写

C++的文件读写就是用用fstream、ifstream和ofstream类
1.头文件:<fstream>

2.三个类
fstream:I/O流   默认读写打开文件
ifstream:I流   默认以读打开文件
ofstream:O流   默认以写打开文件

3.打开文件
方式一:实例化fstream类时默认打开
如:
fstream file(filename, mode);  默认读写打开文件ios::in::ios::out  当文件不存在时不会创建
ifstream file(filename, mode); 默认以读打开文件ios::in   
ofstream file(filename, mode); 默认以写打开文件ios::out  Not:当文件不存在时会创建

方式二:显示调用open函数
fstream file;
file.open(filename, mode);

4.判断文件是否存在
利用ifstream 打开文件失败即为文件不存在
ifstream file(filename);
if( file.good() ){
    cout << "file exist" << endl;
}

5.创建文件
利用ofstream 打开 当文件不存在时会创建
ofstream file(filename);


6.写文件
方式一:<<
ofstream file(filename);
file << msg;   //<<将msg通过file这个文件输出流写到文件中

方式二:write
const char *msg = "I am Bob!";
file.write(msg, strlen(msg));

7.读文件

读之前注意此时文件指针位于何处
可用file.tellg()  file.tellp() 查询
也可用file.seekg(n, post) file.seekp(n, post) 设置
  
方式零:使用 >>
方式一:逐个字符的读:get
方式二:逐行的读:getline
方式三:指定读多少:read


8.判断文件是否打开
ret = file.is_open();
if( ret )
    cout << "Is open" << endl;

9.关闭文件
file.close()

10.demo:

#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>

const char *filename = "D:\\tst.doc";
int main(int argc, char **argv)
{
//文件IO
	//write file and create
	ofstream fileout(filename);
	if (!fileout.good()) {
		cout << "open file failed!" << endl;
		exit(EXIT_FAILURE);
	}
	else
		cout << "open file successful!" << endl;

	const char *msg = "I am Bob!";
	fileout.write(msg, strlen(msg));
	//file << "I am Carl!";
	fileout.close();

	//read file
	ifstream filein(filename);
	if (!filein) {
		cout << "file not exist" << endl;
		exit(EXIT_FAILURE);
	}else
		cout << "file have exist" << endl;

	//way0:get a string use >> 
	//string str;
	//while ( filein.peek() != EOF ) {
	//	filein >> str; //以空格或、换行或结尾标示,为一次读取,要自己做分割符
	//	cout << str;
	//	str.clear();
	//	cout << " ";
	//}

	//way1:get a char use filein.get()
	//char c;
	//while ( filein.peek() != EOF ) {//peek() 获取下一个字符的值,但不会移动文件指针
	//	c = filein.get();  //可以读取空格
	//	cout << c;
	//}

	//way3:get a strline use filein.getline()
/*	char buff[69];
	while ( filein.peek() != EOF) {
		memset(buff, 0, sizeof(buff));
		filein.getline(buff, sizeof(buff));
		cout << buff;
	}*/	

	//way4:get some string use filein.read()
	char buff[69];
	while ( filein.peek() != EOF ) {
		memset(buff, 0, sizeof(buff));
		filein.read(buff, sizeof(buff));
		cout << buff;
	}
	
	filein.close();

	return 0;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值