, , , , , ,

Most of this is rehashed from notes I made several years ago. Download the full source file here: (BasicFileReadWrite.cpp).

In addition to the usual iostream, we include the file stream (fstream):

When declaring the variables, which are the menu option and the text we want to write to the file, we declare usertext as a 256-character string. Strictly speaking, this defines a one-dimensional array 256 characters long.

int option;
char usertext[256];

The menu is followed by a couple of if/then statements, giving the user a choice between reading a file called ‘UserData.dat‘ or writing to it.

Writing Text to a File
The following gets a line of text from the user, and places it in the buffer called ‘usertext‘.
cout<<"Enter text message here: ";
cin.getline ( usertext, 256, '\n' );
cout<<"Your text: "<< usertext <<endl;

Next, we define a destination for writing the contents of usertext. In this case, the destination is the file ‘UserData.dat‘.
ofstream outf("UserData.dat");

Then we simply output the usertext buffer to that file.
outf << usertext << endl;
cout << "Write successful." <<endl;

If I remember correctly, there’s also a function for appending the file, which I haven’t bothered adding yet.

Reading from File
As before, we must define a source file to read from, which again is ‘UserData.dat‘.
ifstream inf("UserData.dat");

Then we create a loop, so the program keeps reading each line of text until all the contents have been read from the file. This is important if code was added for appending the contents of UserData.dat.

while (inf)
std::string strInput;
getline(inf, strInput);
cout << strInput << endl;