C++: What is the best practice of error handling (without exceptions) while reading the file -


consider following example. open file , read first 100 bytes.

std::ifstream fileread; fileread.open("file.txt", std::ios::binary); std::vector<char> buffer(100); fileread.read(buffer.data(), 100); 

can suggest best practice handle possible errors while reading file without using exceptions?

you need know errors you're worried about, , in particular, errors want handle + continue, versus errors want terminate upon encountering.

for example, 1 error might encounter: if file doesn't exist (or don't have permissions/access it)? check pretty easy:

std::ifstream fileread("file.txt", std::ios::binary); if(!fileread) {/*file doesn't exist! do?*/}; 

what if file doesn't have 100 bytes?

std::ifstream fileread("file.txt", std::ios::binary); if(!fileread) {/*file doesn't exist! do?*/} else {     std::vector<char> buffer(100);     fileread.read(buffer.data(), 100);     if(!fileread) {         std::cout << "only " << fileread.gcount() << " bytes read.\n";     } } 

for code you've provided, errors i'd write error handling for. if there other code associated example, error handling may need more extensive.

note none of these examples made use of exception handling: c++ iostreams library [most of] error handling without throwing exceptions.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -