<p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p>

<ul>
<li><p>text files, which would involve some sort of read line function.</p></li>
<li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li>
</ul>

[{'answer_id': 7886, 'author': 'DannySmurf', 'author_id': 1028, 'author_profile': 'https://Stackoverflow.com/users/1028', 'pm_score': 5, 'selected': True, 'text': "<p>There are three ways to do this, depending on your needs. You could use the old-school C way and call <code>fopen</code>/<code>fread</code>/<code>fclose</code>, or you could use the C++ fstream facilities (<code>ifstream</code>/<code>ofstream</code>), or if you're using MFC, use the <code>CFile</code> class, which provides functions to accomplish actual file operations.</p>\n<p>All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (&lt;&lt; and &gt;&gt;) or the read function to read/write blocks of text:</p>\n<pre><code>int nsize = 10;\nstd::vector&lt;char&gt; somedata(nsize);\nifstream myfile;\nmyfile.open(&quot;&lt;path to file&gt;&quot;);\nmyfile.read(somedata.data(), nsize);\nmyfile.close();\n</code></pre>\n<p>Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).</p>\n"}, {'answer_id': 7888, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 5, 'selected': False, 'text': '<p>You need to use an <a href="http://en.cppreference.com/w/cpp/io/basic_ifstream" rel="noreferrer"><code>ifstream</code></a> if you just want to read (use an <code>ofstream</code> to write, or an <code>fstream</code> for both).</p>\n\n<p>To open a file in text mode, do the following:</p>\n\n<pre><code>ifstream in("filename.ext", ios_base::in); // the in flag is optional\n</code></pre>\n\n<p>To open a file in binary mode, you just need to add the "binary" flag.</p>\n\n<pre><code>ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); \n</code></pre>\n\n<p>Use the <a href="http://en.cppreference.com/w/cpp/io/basic_istream/read" rel="noreferrer"><code>ifstream.read()</code></a> function to read a block of characters (in binary or text mode).  Use the <a href="http://en.cppreference.com/w/cpp/string/basic_string/getline" rel="noreferrer"><code>getline()</code></a> function (it\'s global) to read an entire line.</p>\n'}, {'answer_id': 7896, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': -1, 'selected': False, 'text': '<p>fstream are great but I will go a little deeper and tell you about <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow noreferrer">RAII</a>.</p>\n\n<p>The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.</p>\n\n<p><strong>Update</strong>: seems that std::fstream already implements RAII so the code below is useless. I\'ll keep it here for posterity and as an example of RAII. </p>\n\n<pre><code>class FileOpener\n{\npublic:\n    FileOpener(std::fstream&amp; file, const char* fileName): m_file(file)\n    { \n        m_file.open(fileName); \n    }\n    ~FileOpeneer()\n    { \n        file.close(); \n    }\n\nprivate:\n    std::fstream&amp; m_file;\n};\n</code></pre>\n\n<p>You can now use this class in your code like this:</p>\n\n<pre><code>int nsize = 10;\nchar *somedata;\nifstream myfile;\nFileOpener opener(myfile, "&lt;path to file&gt;");\nmyfile.read(somedata,nsize);\n// myfile is closed automatically when opener destructor is called\n</code></pre>\n\n<p>Learning how RAII works can save you some headaches and some major memory management bugs.</p>\n'}, {'answer_id': 24814600, 'author': 'J.p.', 'author_id': 3851030, 'author_profile': 'https://Stackoverflow.com/users/3851030', 'pm_score': 0, 'selected': False, 'text': '<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\nusing namespace std;\n\nvoid main()\n{\n    ifstream in_stream; // fstream command to initiate "in_stream" as a command.\n    char filename[31]; // variable for "filename".\n    cout &lt;&lt; "Enter file name to open :: "; // asks user for input for "filename".\n    cin.getline(filename, 30); // this gets the line from input for "filename".\n    in_stream.open(filename); // this in_stream (fstream) the "filename" to open.\n    if (in_stream.fail())\n    {\n        cout &lt;&lt; "Could not open file to read.""\\n"; // if the open file fails.\n        return;\n    }\n    //.....the rest of the text goes beneath......\n}\n</code></pre>\n'}, {'answer_id': 34267974, 'author': 'Ziezi', 'author_id': 3313438, 'author_profile': 'https://Stackoverflow.com/users/3313438', 'pm_score': 2, 'selected': False, 'text': '<p>To open and read a text file line per line, you could use the following:</p>\n\n<pre><code>// define your file name\nstring file_name = "data.txt";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name);\n\n// check stream status\nif (!input_stream) cerr &lt;&lt; "Can\'t open input file!";\n\n// file contents  \nvector&lt;string&gt; text;\n\n// one line\nstring line;\n\n// extract all the text from the input file\nwhile (getline(input_stream, line)) {\n\n    // store each line in the vector\n    text.push_back(line);\n}\n</code></pre>\n\n<p>To open and read a binary file you need to explicitly declare the reading format in your input stream to be binary, and read memory that has no explicit interpretation using stream member function <a href="http://www.cplusplus.com/reference/istream/istream/read/" rel="nofollow"><code>read()</code></a>:</p>\n\n<pre><code>// define your file name\nstring file_name = "binary_data.bin";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name, ios::binary);\n\n// check stream status\nif (!input_stream) cerr &lt;&lt; "Can\'t open input file!";\n\n// use function that explicitly specifies the amount of block memory read \nint memory_size = 10;\n\n// allocate 10 bytes of memory on heap\nchar* dynamic_buffer = new char[memory_size];\n\n// read 10 bytes and store in dynamic_buffer\nfile_name.read(dynamic_buffer, memory_size);\n</code></pre>\n\n<p>When doing this you\'ll need to <code>#include</code> the header : <code>&lt;iostream&gt;</code></p>\n'}, {'answer_id': 49563356, 'author': 'Nardine Nabil', 'author_id': 9326568, 'author_profile': 'https://Stackoverflow.com/users/9326568', 'pm_score': 1, 'selected': False, 'text': '<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\nusing namespace std;\n\nint main () {\n  ofstream file;\n  file.open ("codebind.txt");\n  file &lt;&lt; "Please writr this text to a file.\\n this text is written using C++\\n";\n  file.close();\n  return 0;\n}\n</code></pre>\n'}, {'answer_id': 49564320, 'author': 'Maria Emil', 'author_id': 9560780, 'author_profile': 'https://Stackoverflow.com/users/9560780', 'pm_score': -1, 'selected': False, 'text': '<pre><code>#include &lt;fstream&gt;\n\nifstream infile;\ninfile.open(**file path**);\nwhile(!infile.eof())\n{\n   getline(infile,data);\n}\ninfile.close();\n</code></pre>\n'}, {'answer_id': 50043136, 'author': 'Kartik Maheshwari', 'author_id': 5213931, 'author_profile': 'https://Stackoverflow.com/users/5213931', 'pm_score': 0, 'selected': False, 'text': '<p>Follow the steps,</p>\n\n<ol>\n<li>Include Header files or name space to access File class.</li>\n<li>Make File class object Depending on your IDE platform ( i.e,\nCFile,QFile,fstream). </li>\n<li>Now you can easily find that class methods to open/read/close/getline or else of any file.</li>\n</ol>\n\n<blockquote>\n<pre><code>CFile/QFile/ifstream m_file;\nm_file.Open(path,Other parameter/mood to open file);\n</code></pre>\n</blockquote>\n\n<p>For reading file you have to make buffer or string to save data and you can pass that variable in read() method.</p>\n'}, {'answer_id': 55663714, 'author': 'Karim Salah', 'author_id': 9571867, 'author_profile': 'https://Stackoverflow.com/users/9571867', 'pm_score': 0, 'selected': False, 'text': '<pre><code>**#include&lt;fstream&gt; //to use file\n#include&lt;string&gt;  //to use getline\nusing namespace std;\nint main(){\nifstream file;\nstring str;\nfile.open("path the file" , ios::binary | ios::in);\nwhile(true){\n   getline(file , str);\n   if(file.fail())\n       break;\n   cout&lt;&lt;str;\n}\n}**\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/7880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432/']