Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fstream reading from a file and writing to a file

Status
Not open for further replies.

SmileeTiger

Programmer
Mar 13, 2000
200
US
Can someone give me some sample code to read from and write to a file in text mode using fstream?


Thanks
 
I'm going from memory on this but you should get the idea. BTW, I'm showing this for Builder but the same principles apply to standard C++. In your header file you will need to add:
Code:
#include <fstream>

Then in your function you could do something like this:
Code:
ofstream ArchiveFile; // opens stream named ArchiveFile for output
ArchiveFile.open(&quot;OutPut.dat&quot;, ios::out | ios::app); // opens for append so original isn't overwritten (out is redundant)
if (!ArchiveFile)
{
    // Stop processing! There is an error.
    Application->MessageBox(&quot;Cannot create archive file.&quot;, &quot;File Error&quot;, MB_OK); // error message box
    return; // get out of function
}

ifstream FNFile; // stream set up for input
FNFile.open(&quot;File2Get.dat&quot;);

if (!FNFile)
{
    // Error opening file! Stop processing.
    Application->MessageBox(&quot;Cannot open file to archive.&quot;, &quot;File Error&quot;, MB_OK);
    ArchiveFile.close(); Close open output file
    return; // Get out of function
}
else
{
    // No errors so let's process
    string ArcLine; // this will be the line to copy from one file to another
    while (getline(FNFile, ArcLine, '\n'))
    {
        // Put line to output
        ArchiveFile << ArcLine << endl;
        // You could also do a character by character copy, too
    }
}

// All done so close files
ArchiveFile.close();
FNFile.close();

There are several ways to go this so don't think this is the only way. You may have to put
Code:
std::
in front of the streams, getline, ios, etc. depending on which version of the compiler you use and how you name your namespaces. James P. Cottingham

When a man sits with a pretty girl for an hour, it seems like a minute. But let him sit on a hot stove for a minute and it's longer than any hour. That's relativity.
[tab][tab]Albert Einstein explaining his Theory of Relativity to a group of journalists.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top