Skip to content

Instantly share code, notes, and snippets.

@brentshermana
Created February 28, 2018 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentshermana/d0f5acc64e7e8ba45c7e058f511bcd58 to your computer and use it in GitHub Desktop.
Save brentshermana/d0f5acc64e7e8ba45c7e058f511bcd58 to your computer and use it in GitHub Desktop.
C++ ifstream reading
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file; // stream object representing an open file
file.open("test.txt"); // path to some text file
if (file.is_open() && file.good()) { // 'good' is a catch-all term that makes sure there were no errors
cout << "reading" << endl;
char buffer[80];
file >> buffer;
if (file.fail()) {
cout << "error during read operation" << endl;
}
else {
cout << buffer;
}
}
else {
cout << "can't read due to error" << endl;
}
// not closing streams can cause memory leaks
file.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment