FileCopy.c#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) /* (A) */
{
FILE *in, *out; /* (B) */
int ch;
if ( argc != 3 ) { /* (C) */
fprintf( stderr, "usage: copy in_file out_file\n" );
exit( EXIT_FAILURE );
}
if ( ( fopen_s(&in,argv[1], "rb" ) ) != 0 ) { /* (D) */
fprintf( stderr, "Can't open %s\n", argv[1] );
exit( EXIT_FAILURE );
}
if ( ( fopen_s(&out,argv[2], "wb" ) ) != 0 ) { /* (E) */
fprintf( stderr, "Can't open %s\n", argv[2] );
fclose( in );
exit( EXIT_FAILURE );
}
while ( ( ch = getc( in ) ) != EOF ) /* (F) */
if ( putc( ch, out ) == EOF ) /* (G) */
break;
if ( ferror( in ) ) /* (H) */
printf( "Error while reading source file.\n" );
if ( ferror( out ) ) /* (I) */
printf( "Error while writing into dest file.\n" );
fclose( in ); /* (J) */
fclose( out ); /* (K) */
return 0;
}
FileCopy.cpp#include <iostream> // for cerr
#include <fstream> //(A)
#include <cstdlib>
using namespace std; //(B)
void print_error(const char*, const char* = ""); //(C)
int main(int argc, char* argv[]) //(D)
{
if (3 != argc)
print_error("usage: copy source dest");
ifstream in( argv[1], ios::binary ); //(E)
if (!in)
print_error( "can't open", argv[1] );
ofstream out( argv[2], ios::binary ); //(F)
if (!out)
print_error( "can't open", argv[2] );
char ch; //(G)
while ( in.get(ch) ) //(H)
out.put( ch ); //(I)
if ( !in.eof() ) //(J)
print_error("something strange happened");
return 0;
}
void print_error(const char* p, const char* p2) { //(K)
cerr << p << ' ' << p2 << '\n'; //(L)
exit(1); //(M)
}
FileCopy.java
import java.io.*; //(A)
class FileCopy { //(B)
public static void main( String[] args ) //(C)
{
int ch = 0;
FileInputStream in = null; //(D)
FileOutputStream out = null; //(E)
if ( args.length != 2 ) { //(F)
System.err.println( "usage: java FileCopy source dest" );
System.exit( 0 );
}
try {
in = new FileInputStream( args[0] ); //(G)
out = new FileOutputStream( args[1] ); //(H)
while ( true ) {
ch = in.read(); //(I)
if (ch == -1) break;
out.write(ch); //(J)
}
out.close(); //(K)
in.close(); //(L)
} catch (IOException e) {
System.out.println( "IO error" );
}
}
}
FileCopy.py' example of file processing in Python ' import sys # access command line arguments (p 338) print 'you entered', len(sys.argv), 'arguments.' print 'they were:', str(sys.argv) #open input file filename = sys.argv[1] print 'input file: ', filename try: inp = open(filename,'r') except IOError, e: print "can't open:",e exit() filename = sys.argv[2] print 'output file: ', filename try: out = open(filename,'w') except IOError, e: print "can't open:",e inp.close() exit() for eachline in inp: out.write(eachline) inp.close() out.close()
Maintained by John Loomis, last updated 29 Dec 2006