On 22/01/2018 04:43, arnuld wrote:
> AIM: To copy a file
> PROBLEM: None
>
> This runs fine, can this be improved. e.g getting rid of while() ?
>
>
> #include <iostream>
> #include <fstream>
>
> int main()
> {
> char ch;
> std::ifstream ifile("tree.c");
> std::ofstream ofile("sample.c");
>
> while(ifile.get(ch))
> ofile.put(ch);
>
> if(!ifile.eof() || !ofile)
> std::cerr << "Something Happened\n";
>
> return 0;
> }
>
>
>
You can use binary mode to handle all kinds of file. See this standard
Microsoft example Program:
<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
#include <iostream>
#include <fstream>
const static int BUF_SIZE = 4096;
using std::ios_base;
int main(int argc, char** argv) {
std::ifstream in(argv[1],
ios_base::in | ios_base::binary); // Use binary mode so we can
std::ofstream out(argv[2], // handle all kinds of file
ios_base::out | ios_base::binary); // content.
// Make sure the streams opened okay...
char buf[BUF_SIZE];
do {
in.read(&buf[0], BUF_SIZE); // Read at most n bytes into
out.write(&buf[0], in.gcount()); // buf, then write the buf to
} while (in.gcount() > 0); // the output.
// Check streams for problems...
in.close();
out.close();
}
<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
You need to close the stream to flush out the buffer otherwise you lose
data.
After you've compiled the file, you simply run at the command prompt
like this:
mycopy tree.c sample.c
mycopy is the name of the executable,
tree.c is your source file;
sample.c is your destination file;