I have some questions about reading/writing to/from a file.

I've been reading up on this subject but can't seem to find anything specific about a few things I'm wondering about.

#1. Should I check if a file is open and associated with a stream before opening that file and associating to that stream?

#2. Should I error check before every consecutive read/ write? For example if I do a getline till eof via loop, should I check the good bit before every getline?

My program is very simple and is the only program using this one file, but I feel like as a good practice I should error check, but I don't want to check unnecessarily.

Thanks.
if you got it open and can read from it, it is pretty rare for anything to go bad until end of file. It can; maybe its a usb disk and the user pulled it out of the socket or its on a network and the cat pulled the cable out of the wall. If you want to go full industrial on it, wrap it up in a try catch block, consider this: http://www.cplusplus.com/reference/ios/ios/exceptions/
1) You should check the status of the file after it is opened. The easiest is simply:

1
2
3
4
std::ifstream ifs("file_to_open");

if (!ifs)
    return (std::cout << "FIle not open\n"), 1;


2) Don't check for eof. Use the return value form std::getline() or extraction to determine the end of data.

1
2
3
for (std::string line; std::getline(ifs, line); ) {
   // Process line here
}


or:

1
2
3
for (int a{}, b{}; ifs >> a >> b; ) {
    // process and b here
}

Last edited on
Awesome. Thanks.
Topic archived. No new replies allowed.