Hi all, how do you do the following operations in C++?
- Opening Files
- Closing Files
- Reading Files
- Writing Files
Hi all, how do you do the following operations in C++?
http://www.cplusplus.com/doc/tutorial/files.html
I personally still use the C style fopen, fread, fwrite, etc, but that is more of preference than actually "correct".
#include <fstream>
int main()
{
std::ifstream inputFile("MyFileName") // Opens a File.
int x;
inputFile >> x; // Reads an integer from a file.
std::string word;
inputFile >> word; // Reads a space separated word from a file.
double y;
inputFile >> y; // Reads a floating point number from the file.
// etc..
} // File AutoMagically closed by going out of scope.
#include <fstream>
int main()
{
std::ofstream inputFile("MyFileName") // Opens a File.
int x = 5;
inputFile << x << " "; // Writes an integer to a file then a space.
inputFile << 5 << " "; // Same Again.
std::string word("This is a line");
inputFile << word << "\n"; // Writes a string to a file followed by a newline
// Notice the difference between reading and
// writing a string.
inputFile << "Write a string constant to a file\n";
double y = 15.4;
inputFile << y << ":"; // Writes a floating point number
// to the file followed by ":".
// etc..
} // File AutoMagically closed by going out of scope.
{
std::ifstream in("foo.txt"); /* opens for reading */
std::ofstream out("bar.txt"); /* opens for writing */
out << in.rdbuf(); /* streams in into out. writing and reading */
} /* closes automatically */
With C++ you've got lots of choices for how to interact with files, especially if you are using one of the many frameworks around, like Qt, wxWidgets, or GLib. To summarize, the standard C++ library uses a streams based model of file access, via std::ifstream and std::ofstream. This is similar to what you see when using std::cout and is what @Martin's post exemplifies. You also have available the standard C library functions for reading and writing files, namely open(), close(), read() and write(). The f*() variants take a FILE pointer rather than a file descriptor. The C variants are more useful when you want to treat a file as a raw stream of bytes, which unfortunately happens more often than it should. While both of these are "portable", constructing paths and handling directories/special files usually isn't, which is why you get things like boost::filesystem.