012
12.11.2003, 14:03 Uhr
virtual
Sexiest Bit alive (Operator)
|
Meine Gedanken dazu sind:
C++: |
#include <stdio.h> #include <stdlib.h> /* Required for demo program only */
/** filecopy * Copies <source> to <target> * @param <source> Name of the source file * @param <target> Name of the target file * @return 0, if succeed, any other return code signs an error: * -1: <source> cannot be opened * -2: <target> cannot be opened * -3: Failed to read from <source> * -4: Failed to write to <target> */ int filecopy( const char* source, const char* target) { int ret = 0; char buffer[8192]; FILE* s = NULL; FILE* t = NULL; size_t len;
/* * Open source */ s = fopen(source, "rb"); if (NULL == s) { return -1; }
/* * Open target */ t = fopen(target, "wb"); if (NULL == t) { fclose(s); return -2; }
/* * Turn off buffering to avoid useless copying * (our buffer is large enough) */ setbuf(s, NULL); setbuf(t, NULL);
/* * Loop to copy file */ do { /* * Read next portion */ len = fread(buffer, 1, sizeof(buffer), s); if (sizeof(buffer)!=len && !feof(s)) { ret = -3; break; }
/* * Write the fetched portion */ if (0 < len) { if (len != fwrite(buffer, 1, len, t)) { ret = -4; break; } } } while (sizeof(buffer)==len);
/* * Close the files */ fclose(t); fclose(s);
/* * Remove target, if an error took place */ if (0 != ret) { remove(target); }
return ret; }
/** Demo * A poor mans copy that copies a file to an other. */ int main( int argc, char** argv) { int fc_ret;
/* * Check command line */ if (argc != 3) { fprintf(stderr, "error: %s: bad commad line.\n" "usage: %s <source> <target>\n", *argv, *argv); exit(EXIT_FAILURE); }
/* * Copy files */ fc_ret = filecopy(argv[1], argv[2]); if (0 != fc_ret) { fprintf(stderr, "error: %s: cannot copy %s to %s: ", argv[0], argv[1], argv[2]);
switch (fc_ret) { case -1: fprintf(stderr, "cannot open %s for reading.\n", argv[1]); break; case -2: fprintf(stderr, "cannot open %s for writing.\n", argv[2]); break; case -3: fprintf(stderr, "cannot read from %s.\n", argv[1]); break; case -4: fprintf(stderr, "cannot write to %s.\n", argv[2]); break; default: fprintf(stderr, "unknown error.\n"); break; } exit(EXIT_FAILURE); }
return EXIT_SUCCESS; }
|
Durch ausschalten des Bufferings sollte sich das 3 Malige Kopieren auf 1 Mal reduzieren lassen... -- Gruß, virtual Quote of the Month Ich eß' nur was ein Gesicht hat (Creme 21) |