ch2-Scopy (Copy files using a string)
Chapter_2 Exercise_2-2 HeYou | FillString Exercise_2-3 |
Scopy.cpp TCP1, p. 111 download
// Copy one file to another, a line at a time
#include <string>
#include <fstream>
using std::string;
using std::ifstream;
using std::ofstream;
int main()
{
ifstream in("Scopy.cpp"); // Open for reading
ofstream out("Scopy2.cpp"); // Open for writing
string s;
while(getline(in, s)) // Discards newline char
{out << s << "\n";} // must add it back
}
/*
g++ Scopy.cpp -o Scopy
./Scopy
g++ Scopy2.cpp -o Scopy2
./Scopy2
rm Scopy2* // clean
*/
Notes:
It is good coding practice to enclose in braces the single statement of a loop, like
while() above. It is easier to read, to delimit from other parts of the code, and you may decide to add other statements later on.
You may compile and run Scopy2.cpp, with the same result (Scopy2.cpp will be overwritten with exactly the same content):
g++ Scopy2.cpp -o Scopy2
./Scopy2
At the end we remove the created files Scopy2.cpp and Scopy2:
rm Scopy2*
Chapter_2 Exercise_2-2 HeYou | BACK_TO_TOP | FillString Exercise_2-3 |
Comments
Post a Comment