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!

How to read data from a file then write to another file with condition

Status
Not open for further replies.

miketm

Programmer
Oct 19, 2003
18
AU
Hi everyone,

Please provide me some help on file reading and writing. First, I would like to know how to read data from a file and then write it to another file. I have been searching and seen examples of writing to the screen (Cout)only or writing some short strings to a file but not the whole data file from the input file.

Second, Is it possible to manipulate the writing by setting some conditions such as: If the word "ONE" appears in the file then do someting, "TWO" and "THREE" do something else ? as it can read a single character at a time only so how can it know the word "ONE, TWO or THREE" occur? We can use getword() or something but that people say it will cause errors (problem in new-line character).


ifstream OpenFile("test.doc");
char ch;
while(!OpenFile.eof())
{
OpenFile.get(ch);
cout << ch; //wrting to screen not to a file
}
OpenFile.close();

So how can we write what read from &quot;test.doc&quot; to another file&quot;? Please help. Thanks






 
Hi,

Concerning the reading from a file and the writing to another file, do something like this :

#include <ifstream>
#include <ofstream>
#include <assert.h>

using namespace std;

void test_read_write ()
{
ifstream in_file (&quot;infile.txt&quot;);
ofstream out_file (&quot;outfile.txt&quot;);
assert (in_file.is_open () && out_file.is_open ());

char read_char;
while (!in_file.eof ())
{
in_file.get (read_char);
out_file << read_char;//or : out_file.put (read_char)
}
in_file.close (); //normally, fstream destructors
out_file.close ();//close opened files.
}

For your second problem, you can record in a temporary string variable what you read and then test if that &quot;temp&quot; matches the particular words &quot;ONE&quot;, &quot;TWO, etc.

--
Globos
 
Hi Globos,

Thank you very very much for your time and help. I will be working on it, as I don't have much experience in C++, it will take me a long while to explore and learn. Your program seems very logic and you are giving me a great help, I understand it clearly. Bye for now.

Thanks!
Miketm
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top