c++ io 学习

1. 几种读取文件的方式 get(char&), >>(char*), getline(char*, capacity);

#include <iostream>
#include <fstream>
using namespace std;

void main(){
	ofstream file("main.txt");
	file <<"hello stephen"<< endl;
	file <<"your first name is xing"<< endl;
	file.close();

	char ch;
	ifstream file2("main.txt");
	while (!file2.eof()){
		file2.get(ch);
		cout << ch;
	}
	file2.close();

	cout << "======================================" << endl;
	file2.open("main.txt");
	char str[30];
	while (!file2.eof()){
		file2 >> str;
		cout << str;
	}

	file2.close();

	cout << "======================================" << endl;
	file2.open("main.txt");
	char strLine[1024];
	while (!file2.eof()){
		file2.getline(strLine, 1024);
		cout << strLine << endl;
	}

	file2.close();
}

2.文件的几种错误状态,有所了解即可

#include <iostream>
#include <fstream>
using namespace std;


void main()
{
	ofstream File1("file2.txt"); //建立file2.txt
	File1.close();

	//下面的检测代码将会返回错误,这是因为我使用了ios::noreplace打开模式
	//它模式在试图打开一个已存在的文件时会返回错误
	ofstream Test("file2.txt",ios::_Noreplace);

	//上一行将导致ios::failbit错误,我们这就将其演示出来
	if(Test.rdstate() == ios::failbit){
		cout << "Error, not fatal error...!\n";
	}

	Test.clear(ios::goodbit); //将当前状态重置为ios::goodbit

	if(Test.rdstate() == ios::goodbit) {//检测程序是否已经正确地施行了设置
		cout << "Fine!\n";
	}

	Test.clear(ios::eofbit); //将状态标志设为ios::eofbit. 无实际用途.

	if(Test.rdstate() == ios::eofbit) {//检测是否已经正确地施行了设置       
		cout << "EOF!\n";
	}

		Test.close();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值