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();

}

你可能感兴趣的:(c++ io 学习)