How to check file status in C++

1 Answer

0 votes
#include <iostream>
#include <fstream>

using std::cout;
using std::endl;
using std::ifstream;

void check_file_status(ifstream &ifs)
{
	std::ios::iostate state;

	state = ifs.rdstate();

	if (state & std::ios::eofbit)
		cout << endl << "EOF" << endl;
	else if (state & std::ios::failbit)
		cout << endl << "Non-Fatal I/O error" << endl;
	else if (state &std::ios::badbit)
		cout << endl << "Fatal I/O error" << endl;
}

int main()
{
	ifstream ifs("d:\\data.txt");

	if (!ifs) {
		cout << "Error open file" << endl;
		return 1;
	}

	char ch;
	while (ifs.get(ch)) {
		cout << ch;
		check_file_status(ifs);
	}

	check_file_status(ifs);  
	ifs.close();

	return 0;
}


/*
run:

c c++ java
EOF

*/

 



answered Jul 2, 2018 by avibootz

Related questions

1 answer 159 views
159 views asked Apr 8, 2018 by avibootz
2 answers 1,124 views
1 answer 167 views
1 answer 192 views
...