Dave's Brain

Browse - Programming Tips - How can I read a text file using ifstream?

Date: 2014oct7
Language: C++
Level: Beginner

Q.  How can I read a text file using ifstream?

A.  There are many examples of this.  But this is how I like to do it.
I don't import the std namespace.  I call is_open() right after
open(), which is void.  I use a fixed size buffer rather than a string
for speed.

#include <iostream> #include <fstream> bool readfile(const char *filename) { char buf[5 * 1024]; std::ifstream myfile; myfile.open(filename, std::ifstream::in); if (!myfile.is_open()) { cerr << "Could not open the file"; return false; } for (;;) { if (!myfile.getline(buf, sizeof(buf))) { // Its eof, possibly do something break; } cout << buf; cout << '\n'; } myfile.close(); return true; } int main () { readfile("example.txt"); }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.