Reading and Writing Files With std::fstream

Among the many things made easier in object-oriented programming is file IO. Gone are the days of manipulating FILE pointers, now there is a C++ stream class for handling file operations: std::fstream. Like all stream objects, fstream objects use operators << and >> to perform input and output. Let’s look at an example.

int main(int argc, char** argv) { std::fstream read("/tmp/read_from", std::fstream::in); std::fstream write("/tmp/write_to", std::fstream::out); std::string buffer; while (!read.eof()) { read >> buffer; std::cout << buffer << std::endl; write << buffer << std::endl; buffer = ""; } read.close(); write.close(); return 0; }

This program does 3 things: 1) reads in the contents of read_from, 2) outputs the contents to cout, and 3) writes the contents to write_to.

First, we declare two fstreams, read and write. We pass to the constructor the absolute paths of the files to read, and the magic constants std::fstream::in and std::fstream::out respectively. We also declare a buffer string.

When you attempt to read past the end of a file, it sets fstream.eof to true. We can use this to loop through a file and read it in. We do this in our while loop.

Within our loop we take input from read, we output it to cout and write, then we reset our buffer string. After this is all done, we close our two fstreams and return 0.

This function has one problem. fstream operator<< tokenizes the file contents, stripping all whitespace. Therefore, after this program is run, write_to will not be the same as read_from. This is what happens if we ldiff them.

#ldiff read_from write_to words words more words | more non-indented words | words > non-indented > words

Probably not what you wanted to happen. So, how can we prevent this? There is a function getline(). Let’s modify our example to use getline():

int main(int argc, char** argv) { std::fstream read("/tmp/read_from", std::fstream::in); std::fstream write("/tmp/write_to", std::fstream::out); std::string buffer; while (!read.eof()) { getline(read, buffer); std::cout << buffer << std::endl; write << buffer; if (!read.eof()) write << std::endl; } read.close(); write.close(); return 0; }

This program functions as expected, producing an exact copy of read_from…

#ldiff read_from write_to words words more words more words non-indented words non-indented words

For more info on the use of fstream, see this cplusplus.com reference page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: