> How to read from file in C++?

How to read from file in C++?

Posted at: 2014-12-18 
I tried fopen and all that but I get an error and I don't remember if fopen is for C or C++. How do I read from a file in C++?

fopen can be used for both C and C++. Being an old C guy, I still use fopen instead of iostream libraries.

What error do you get? When you specify the file name you must include the path if the file is not in the same directory as the .exe file. Also the \ in the path must be escaped.

Example: "C:\\temp\\test.txt"

FILE* fPtr = 0;

fPtr = fopen("C:\\temp\\test.txt", "w"); //w is for write, r for read, b for binary, etc...

You can use fopen & friends in C++. In fact, I prefer them to C++'s iostreams.

So if you had a problem with fopen, it was how you used it, not inherent to using fopen with C++.

fopen() is C. For c++ it's fstreams and fstream.open().

See the documentation for std:: ifstream

I tried fopen and all that but I get an error and I don't remember if fopen is for C or C++. How do I read from a file in C++?