views:

330

answers:

4

Hi all, how do you do the following operations in C++?

  1. Opening Files
  2. Closing Files
  3. Reading Files
  4. Writing Files
+2  A: 

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".

grieve
I prefer the standard file functions to iostream as well :)
Jason Coco
Absolutely. iostream makes it so difficult to do basic writing and custom formatting. I don't understand why it's considered an 'improvement'.
Kieveli
+10  A: 

Reading

#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.

Writing

#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.
Martin York
great answer! thank's Martin
Wasayef K
+4  A: 

All at once

{ 
    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 */
Johannes Schaub - litb
+1  A: 

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.