Rolf Magnus wrote on Apr 27, 5:17 pm
abecedar...@spambob.com wrote: I don't think it's that easy. Show an implementation with full error
handling?!
#include <iostream>
#include <cctype>
#include <fstream>
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "Usage: " << argv[0]
<< " <infile> <outfile>\n";
return EXIT_FAILURE;
}
std::ifstream infile(argv[1], std::ios_base::binary);
std::ofstream outfile(argv[2], std::ios_base::binary);
char c;
while (infile.get(c) && outfile.put(c));
if (!outfile)
{
std::cerr << "Error writing output file\n";
return EXIT_FAILURE;
}
if (!infile.eof())
{
std::cerr << "Error reading input file\n";
return EXIT_FAILURE;
}
}
- you don't check if outfile exists, you just destroy it.
- you don't close outfile, you let the destructor do it. If close()
fails (e.g. because the data cannot be flushed to disk) your program
reports 'success'. Definitely a bug.
- you don't perform any cleanup in case of error.
- 'while (infile.get(c) && outfile.put(c))' is very slow (not an error
but ...).
- ...
In the worst case you destroy an existing file, create a corrupted
(half-written) file with the same name and report success. It's not
that easy to ... . Not entirely your fault though. std::iostream is a
toy library not suitable for professional programming.
Abe